`
xhgrid
  • 浏览: 13867 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

How to Execute Javascript on Ajax return

阅读更多
Ajax is a nice technology to develop more interactive web pages and enhance user experience. with Ajax you can send a request to your web server with JavaScript and get the response, and show it on your page without refreshing the page .The popular problem for developer regarding to use of Ajax is when you need to some JavaScript in your web server response to be run. for example when you want to check the user input in a form's field and return a message by JavaScript alert function if its wrong, but because of that JavaScript code just import or innerHTML to your page like some text it doesn't not not actually execute to show an alert . the solution to this problem is eval() function which can execute the JavaScript code given to it as argument.

But another problem can be when your response is mixed with HTML and JavaScript together. In that case you have to parse the response first and poll out the JavaScript code out of it and run it. But make sure to have tags at beginning and end of you JavaScript.

function PaseAjaxResponse(somemixedcode)
{
var source = somemixedcode;
var scripts = new Array();
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
scripts.push(source.substring(s_e+1, e));
source = source.substring(0, s) + source.substring(e_e+1);
}
for(var x=0; x<scripts.length; x++) {
try {
eval(scripts[x]);
}
catch(ex) {
}
}
return source;
}
This function first check the response and poll out all the and then in a while loop execute the script by eval() function one by one . and here is an exmple of how to use it with Ajax in Jquery


function doAjaxPost(divname, mydata) {
$.ajax({
   type: \"POST\",
   url: \"ajax.php\",
   cache: false,
   data: mydata,
   success: function(msg){
   document.getElementById(divname).innerHTML = msg;
   PaseAjaxResponse(msg);
   }
});
}

This function get a divname which is id of DIV you want to show the response there and mydata is the request ( like : ?show&code=12) you want to post to ajax.php page

http://www.yasha.co/Ajax/execute-javascript-on-Ajax-return/article-2.html
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics