Jquery passing data to ajax function

2020-07-14 00:13发布

问题:

I'm having problems passing data values to the Jquery Ajax function.

I have been using the getJSON function and that was working fine but now I want to use the ajax function and I can't work out how to pass in values.

       $.ajax({
            type: "POST",
            url: '../../../WebServices/ImageLibrary.svc/getimagesinfolder',
            dataType: 'json',
            data: "{ 'id', '2' }",
            contentType: "application/json; charset=utf-8",
            success: function (data)
            {
                alert('hello');
            }
        });

Is this right? Can anyone tell me where i'm going wrong?

Thanks

回答1:

You have invalid JSON:

"{ 'id', '2' }"

I would recommend you calling it like this as it will take care of properly encoding your parameters:

$.ajax({
    type: "POST",
    url: '../../../WebServices/ImageLibrary.svc/getimagesinfolder',
    dataType: 'json',
    data: JSON.stringify({ id: '2' }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        alert('hello');
    }
});


回答2:

Use this: data: { 'id': '2' },