通过在Ajax响应的JavaScript函数 [英] Pass JavaScript function in ajax response

查看:181
本文介绍了通过在Ajax响应的JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图返回一个回调从一个AJAX提交的表单。用户提交表单,服务器进程,并返回有效响应,即一条错误消息,也是一个JavaScript函数,可以执行的操作。我使用Zepto.js faling回jQuery的依赖于浏览器。

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请求是:

$.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

在返回给浏览器的回调函数应该解雇。我希望服务器返回的回调,所以我可以用同一个JavaScript 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.

,我需要到该数据类型更改为脚本?不过,我认为这只是加载的.js文件,并不是code块。

Would I need to change the dataType to script? However I thought this was just for loading .js files, not blocks of code.

任何帮助AP preciated。

Any help appreciated.

推荐答案

这里的总体感觉是我在错误的方式接近这一点。因此,修订后的code:

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');
}

和我的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.

这篇关于通过在Ajax响应的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆