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
`SyntaxError: Failed to execute 'JSON' on 'Response'` 这是一个常见的 JavaScript 错误提示,通常出现在处理 `fetch()` 或其他异步请求返回的数据时。它表示程序尝试将响应体解析为 JSON 格式时失败了。 ### 可能的原因及解决办法: 1. **服务器未返回合法的 JSON 数据** - 确认服务端是否正常工作,并检查其返回值确实是 JSON 格式的字符串。如果返回的是 HTML、纯文本或其他非 JSON 内容,则会引发此错误。 - 解决方案:联系后端开发者确认 API 的正确性和数据结构;也可以通过打印出整个 Response 对象查看实际内容(例如 `console.log(response)`),判断是否存在异常情况。 2. **网络连接中断或超时导致接收不到完整数据包** - 如果因网速过慢等原因只接收到部分信息就立即开始转换成 JS 对象,则会出现语法不符合规范的情况。 - 解决方法:增加 timeout 设置或者对 fetch 加入 try...catch 块捕获潜在的问题并给出友好的反馈给用户界面。 3. **忘记等待 Promise 完全 resolve 后再操作结果集** - 使用 async-await 编程风格的时候特别需要注意顺序问题——即需要明确地让代码暂停下来等到所有的 promise 都完成之后才继续往下走下一步骤。 ```javascript // 正确示例: try { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); const data = await response.json(); // 等待解析成功后再访问data变量 } catch (err){ console.error('Fetch problem:', err.message); } ``` 以上就是在遇到此类 SyntaxErrors 时候可以采取的一些步骤建议!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值