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条)

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧