开发者

jQuery Ajax with JSON

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 P开发者_开发技巧rototype.js if there is a better way of doing it.


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


You can pass the json object as data parameter to jquery ajax. In order for test_func to get called you have to provide the success handler to ajax method.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜