简体   繁体   中英

JQuery.ajax(): Issue with parameter data when consuming a WCF Service

I'm using JQuery to consume a WCF Service. Actually this works fine:

var para = ' { "Parameter" : { "ID" : "5", "Name" : "Peter" } }'
$.ajax({
   type: "POST",
   contentType: "application/json",
   data: para,
   url: url
   success: success
});

But I don't want to pass the data parameter as String and I think it should be possible to pass ist as array in any way. Like that:

var para = { "Parameter" : { "ID" : 5, "Name" : "Peter" } }

But when I try this I'm getting an error. What I'm doing wrong?

Thanks

var para = '{ "ID" : "5", "Name" : "Peter" }';
$.ajax({
   type: "POST",
   data: para,
   url: url
   success: success
});

If you format it like this you should be able to get the values as

$_POST will return array('ID' => '5', 'Name' => 'Peter');

but you can also access it by doing:

$_POST['ID'] and $_POST['Name']

Also you could make use of the jquery post function:

var para = '{ "ID" : "5", "Name" : "Peter" }';
$.post(
    url, 
    para
);

You can use JSON.stringify function from the json2.js . Then you ajax call will be

var para = { Parameter : { ID :5, Name : "Peter" } };
$.ajax({
   type: "POST",
   contentType: "application/json",
   data: JSON.stringify(para),
   url: url
   success: success
});

The usage of manual conversion to the JSON string is not good because of possible spatial characterless in the string which must be escaped (see http://www.json.org/ for details).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM