如何在jQuery $ .ajax方法中传递json?

时间:2012-02-07 20:43:47

标签: jquery json

我有以下json数据,我想使用$ .ajax将其传递给服务器。我尝试了很多次,没有返回,这是假设返回另一个json对象。请帮忙

$(function() {
        var parameters = {
            "firstName": "Saumil",
            "lastName": "Jhaveri",
            "email": "test@test.com",
            "address": "650+Townsend+St,+St.+325",
            "city": "San+Francisco",
            "state": "California",
            "zipCode": "94103",
            "country": "United+States",
            "phone": "312&375&1884",
            "industry": "Accounting",
            "organization": "Citrix",
            "jobTitle": "Software+Engineer",
            "purchasingTimeFrame": "1&3+months",
            "roleInPurchaseProcess": "Decision+Maker",
            "numberOfEmployees": "1&20",
            "questionsAndComments": "No+Comments!",
            "responses": [{
                "questionKey": 152,
                "responseText": "Fantastic!"
            }, {
                "questionKey": 151,
                "answerKey": 152
             }]
            };
          var jsonData=$.toJSON(parameters);  
    $.ajax({
        type: "POST",
        url: "https://api.citrixonline.com/G2W/rest/organizers/2934047/webinars/439546160/registrants?oauth_token=57f9454c6aecec65adef1ca66cbfde02",
        data: jsonData,
            contentType: "application/json",
            dataType: "json",
            success: function(data) {
                $('#key').html(data.registrantKey);
                $('#url').html(data.joinUrl);
            }
        });
    });

这是我要显示返回数据的div。

<div id="key"></div>
<div id="url"></div>

我无法控制发送数据的网址,但据说我会收到如下响应:

     HTTP/1.1 201 OK
 Content-Type: application/json
 {
 "registrantKey":5678,
 "joinUrl":"https://www1.gotomeeting.com/join/123456789/5678"
 }

1 个答案:

答案 0 :(得分:1)

$.toJSON方法将返回格式为JSON的字符串。如果你给它一个键,那么这个字符串可以是POSt变量的值:

$.ajax({
    type: "POST",
    url: "https://api.citrixonline.com/G2W/rest/organizers/2934047/webinars/439546160/registrants?oauth_token=57f9454c6aecec65adef1ca66cbfde02",
    data: 'jsonData=' + jsonData,
        contentType: "application/json",
        dataType: "json",
        success: function(data) {
            $('#key').html(data.registrantKey);
            $('#url').html(data.joinUrl);
        }
    });

我假设您使用的$.toJSON方法是此插件的一部分:http://code.google.com/p/jquery-json/