如何在数据之前执行 jQuery 回调?
我有一个简单的帖子,它执行了作为脚本返回的数据,如下所示:
$.post("/home", { foo: 'bar' }, function(){
//callback function
}, "script");
发生的情况如下:
- 请求被发送
- 一段 JS 代码作为 响应并执行
- 执行回调
我需要在执行返回的 JS 之前执行回调。 有办法实现这一点吗?
谢谢!
I have a simple post, which executed the data returned as a script as such:
$.post("/home", { foo: 'bar' }, function(){
//callback function
}, "script");
Here's what happens:
- The request gets sent
- A piece of JS code is returned as a
response and executed - The callback is executed
I need the callback to be executed before the returned JS is executed.
Is there a way to achieve this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用在发送 ajax 请求之前执行的“BeforeSend”选项:
希望这
会有所帮助。
此致。
何塞
You could use "BeforeSend" option that is executed before send the ajax request:
}
Hope this helps.
best regards.
Jose
这个 $.post() 函数不会自动执行返回的 JS。它可能是在回调函数中执行的。
This $.post() function does not automatically execute the JS which is returned. It is probably executed in the callback function.
您无法更改 jQuery 处理请求的方式。毕竟,回调就是回调,工作完成后就会执行!但是,您可以将
dataType
设置为"text"
,然后评估您的 Javascript。例如:
** UPDATE **
这是 jQuery 在内部执行的操作(片段):
因此,从 Ajax 请求中取出
globalEval
并执行它不存在安全风险在回调函数中。You can't change how jQuery handle the request. After all, a callback is a callback and it gets executed once the job is done! You can, however, set the
dataType
to"text"
and then eval your Javascript.Ex:
** UPDATE **
This is what jQuery does internally (snipped) :
So, there is no security risk with taking the
globalEval
out of the Ajax request and executing it in the callback function.使用
$.ajax()
并构建您自己的脚本标记。Use
$.ajax()
and build your own script tag.