douqihou7537 2011-07-26 18:52
浏览 51
已采纳

带JSON的jQuery Ajax

I'm coming from Prototype.js where I handle all of my ajax calls like:

function ajax_request (page, func) {
    new Ajax.Request (page, { method : 'post', parameters : { JSON : func } } );
}

function test_func (data) {
    alert(data);
}

//example
ajax_request('/ajax.php', 'test_func');

And the PHP:

$data_array = array()
$data_array['test'] = 'test data';    

header("{$_SERVER['SERVER_PROTOCOL']} 200 OK", True, 200);
header('Content-type: application/javascript');
echo $_POST['JSON'] . '(' . json_encode($data_array) . '); //';

I'm trying to accomplish something similar in jQuery, but it doesn't seem to be working the same way. I'm using the following with jQuery, which makes the request, but the test_func doesn't get called.

function ajax_request (page, func) {
    $.ajax({
        url: page,
        cache: false,
        type: 'POST',
        data: 'JSON=' + func
    });
}

It is quite likely I've been doing this the best way from the beginning, so the answer doesn't have to replicate the method used with Prototype.js if there is a better way of doing it.

  • 写回答

2条回答 默认 最新

  • dragon7088 2011-07-26 18:56
    关注

    From my best interpretation of what you're asking, I'd say that the parametersoption from Prototype.js is the same thing as the data param in jQuery. Although jQuery does allow you to use a URL formatted query string as data, I recommend pass an object for it to serialize properly:

    function ajax_request (page, func) {
        $.ajax({
            url: page,
            cache: false,
            type: 'POST',
            data: {
                JSON: func
            }
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog