开发者

jQuery.ajax "data" parameter syntax

I am trying to pass the contents of a javascript variable to the 开发者_运维技巧server for processing. I can pass static strings no problem but when I pass a variable containing a string, the WebMethod is not called. Here is my code: (Client)

function expand(checkbox) 
{
    var selectedrow = checkbox.parentNode.parentNode;
    var rowindex = selectedrow.rowIndex;
    var parent = document.getElementById("parentTable");
    var NextRow = parent.rows[rowindex + 1];

    var cols = selectedrow.cells[1];
    var ID = cols.firstElementChild.attributes.value;


    $.ajax({
        type: "post",
        url: "Playground.aspx/childBind",
        data: "{sendData: ID}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) { alert("successful!" + result.d); }
    })

    NextRow.style.visibility = "visible";
}

(Server)

[WebMethod]
    public static string childBind(string sendData)
    {
        return String.Format("Hello");
    }

Now, if I were to try data: "{sendData: "ok"}", the WebMethod gets called and returns a response. How is my syntax wrong?


You don't have to pass it as a string. Since ID is a javascript variable you have to pass its value. When you pass data as "{sendData: ID}" it will not pass the value of ID.

Try this

data: { sendData: ID }


You were sending a string instead of an object ("{sendData: ID}" instead of {sendData: ID}). And the data you were sending wasn't JSON. So remove the contentType line and change the data line. You should re-write this as:

$.ajax({
    type: "post",
    url: "Playground.aspx/childBind",
    data: {sendData: ID},
    dataType: "json",
    success: function (result) { alert("successful!" + result.d); }
})

You can also write this, if you want to send JSON:

$.ajax({
    type: "post",
    url: "Playground.aspx/childBind",
    data: $.getJSON({sendData: ID}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (result) { alert("successful!" + result.d); }
})


Since you are using jQuery run these tests for the answer:

var ID = 45;

var x = "{sendData: ID}";

alert(jQuery.isPlainObject(x));  // false

var y = { sendData: ID};

alert(jQuery.isPlainObject(y)); // true

Here is the jsFiddle:

http://jsfiddle.net/3ugKE/


You are passing in 'ID' as a string rather than a variable. All you need to do is remove the quotes around your data object.

Further reading on JSON and javascript objects:

http://www.json.org/

http://www.w3schools.com/js/js_objects.asp


you can use this code :

$.ajax({
        type: "post",
        url: "Playground.aspx/childBind",
        data: JSON.stringify({sendData: ID}),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) { alert("successful!" + result.d); }
    })
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜