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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值