I'm trying to return a callback from an AJAX submitted form. The user submits a form, the server processes and returns the valid response, i.e. an error message and also a JavaScript function that could perform an action. I'm using Zepto.js faling back to jQuery depending on browser.
我试图从AJAX提交的表单返回回调。用户提交表单、服务器进程并返回有效响应,即错误消息和可以执行操作的JavaScript函数。我用Zepto。js通过浏览器返回到jQuery。
My ajax request is:
我的ajax请求是:
$.ajax({
success: function(data, status, xhr) {
data.callback();
},
url: form.attr('action'),
data: form.serialize(),
dataType: 'json'
});
On the server I want to return something like:
在服务器上,我想返回如下内容:
// PHP code
?>
{
return: false,
error: 'Sorry, we couldn’t find an account with that username or password.',
callback: function() {
console.log('this is the callback');
}
}
<?php
// more PHP code
When returned to the browser callback function should fire. I want the server to return the callback so I can use the same JavaScript code and have it respond accordingly to the server response.
当返回到浏览器回调函数时,应该触发。我希望服务器返回回调,以便我可以使用相同的JavaScript代码,并让它相应地响应服务器响应。
Would I need to change the dataType to script? However I thought this was just for loading .js files, not blocks of code.
我需要将数据类型更改为脚本吗?但是,我认为这只是用于加载.js文件,而不是代码块。
Any help appreciated.
任何帮助表示赞赏。
2 个解决方案
#1
1
The general feeling here is I am approaching this in the wrong way. So revised code:
这里的普遍感觉是,我用了错误的方式来处理这个问题。所以修改后的代码:
$.ajax({
success: function(data, status, xhr) {
var callback = data['callback'];
callback();
},
url: form.attr('action'), // in this example it's badLogin
data: form.serialize(),
dataType: 'json'
});
// callback specified in PHP
badLogin: function() {
console.log('bad login');
}
And my PHP
和我的PHP
if (!$valid) {
?>
{
"return": false,
"error": "Sorry, we couldn’t find an account with that username or password.",
"callback": "badLogin"
}
<?php
}
Thanks for pointing me in the right direction.
谢谢你给我指出了正确的方向。
#2
0
You can always return the code as a string and use eval()
if you are absolutely sure that the string will always be correct and no code can be injected.
如果您绝对确信该字符串始终是正确的,并且不能注入任何代码,那么可以将代码作为字符串返回并使用eval()。
#1
1
The general feeling here is I am approaching this in the wrong way. So revised code:
这里的普遍感觉是,我用了错误的方式来处理这个问题。所以修改后的代码:
$.ajax({
success: function(data, status, xhr) {
var callback = data['callback'];
callback();
},
url: form.attr('action'), // in this example it's badLogin
data: form.serialize(),
dataType: 'json'
});
// callback specified in PHP
badLogin: function() {
console.log('bad login');
}
And my PHP
和我的PHP
if (!$valid) {
?>
{
"return": false,
"error": "Sorry, we couldn’t find an account with that username or password.",
"callback": "badLogin"
}
<?php
}
Thanks for pointing me in the right direction.
谢谢你给我指出了正确的方向。
#2
0
You can always return the code as a string and use eval()
if you are absolutely sure that the string will always be correct and no code can be injected.
如果您绝对确信该字符串始终是正确的,并且不能注入任何代码,那么可以将代码作为字符串返回并使用eval()。