Jquery Ajax 将 json 发布到 webservice
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6323338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Ajax Posting json to webservice
提问by Code Pharaoh
I am trying to post a JSON object to a asp.net webservice.
我正在尝试将 JSON 对象发布到 asp.net 网络服务。
My json looks like this:
我的 json 看起来像这样:
var markers = { "markers": [
{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }
]};
I am using the json2.js to stringyfy my json object.
我正在使用 json2.js 来字符串化我的 json 对象。
and i am using jquery to post it to my webservice.
我正在使用 jquery 将其发布到我的网络服务。
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
data: markers,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
I am getting the following error:
我收到以下错误:
"Invalid JSON primitive:
“无效的 JSON 原语:
I have found a bunch of posts relating to this and it seems to be a really common problem but nothing i try fixes the issue.
我发现了一堆与此相关的帖子,这似乎是一个非常普遍的问题,但我没有尝试解决该问题。
When firebug what is being posted to the server it looks like this:
当萤火虫发布到服务器的内容时,它看起来像这样:
markers%5B0%5D%5Bposition%5D=128.3657142857143&markers%5B0%5D%5BmarkerPosition%5D=7&markers%5B1%5D%5Bposition%5D=235.1944023323615&markers%5B1%5D%5BmarkerPosition%5D=19&markers%5B2%5D%5Bposition%5D=42.5978231292517&markers%5B2%5D%5BmarkerPosition%5D=-3
标记%5B0%5D%5Bposition%5D=128.3657142857143&markers%5B0%5D%5BmarkerPosition%5D=7&markers%5B1%5D%5Bposition%5D=235.1944023323615&markers%5Bposition%5Bposition%Dmarkers%5Bposition%5Bposition%Dmarkers%Position%5Bposition%5D=7&markers%5B1%5D%5Bposition%5D 5D=42.5978231292517&markers%5B2%5D%5BmarkerPosition%5D=-3
My webservice function that is being called is:
我正在调用的网络服务功能是:
[WebMethod]
public string CreateMarkers(string markerArray)
{
return "received markers";
}
回答by Dave Ward
You mentioned using json2.js to stringify your data, but the POSTed data appears to be URLEncoded JSON You may have already seen it, but this post about the invalid JSON primitivecovers why the JSON is being URLEncoded.
您提到使用 json2.js 对您的数据进行字符串化,但 POSTed 数据似乎是 URLEncoded JSON 您可能已经看过它,但这篇关于无效 JSON 原语的文章涵盖了为什么 JSON 被 URLEncoded。
I'd advise againstpassing a raw, manually-serialized JSON string into your method. ASP.NET is going to automatically JSON deserialize the request's POST data, so if you're manually serializing and sending a JSON string to ASP.NET, you'll actually end up having to JSON serialize your JSON serialized string.
我建议不要将原始的、手动序列化的 JSON 字符串传递到您的方法中。ASP.NET 将自动对请求的 POST 数据进行 JSON 反序列化,因此如果您手动序列化并将 JSON 字符串发送到 ASP.NET,您实际上最终必须对 JSON 序列化字符串进行 JSON 序列化。
I'd suggest something more along these lines:
我建议在这些方面做更多的事情:
var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }];
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ Markers: markers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
The key to avoiding the invalid JSON primitive issue is to pass jQuery a JSON string for the data
parameter, not a JavaScript object, so that jQuery doesn't attempt to URLEncode your data.
避免无效 JSON 原语问题的关键是向 jQuery 传递data
参数的 JSON 字符串,而不是 JavaScript 对象,以便 jQuery 不会尝试对您的数据进行 URLEncode。
On the server-side, match your method's input parameters to the shape of the data you're passing in:
在服务器端,将您的方法的输入参数与您传入的数据的形状相匹配:
public class Marker
{
public decimal position { get; set; }
public int markerPosition { get; set; }
}
[WebMethod]
public string CreateMarkers(List<Marker> Markers)
{
return "Received " + Markers.Count + " markers.";
}
You can also accept an array, like Marker[] Markers
, if you prefer. The deserializer that ASMX ScriptServices uses (JavaScriptSerializer) is pretty flexible, and will do what it can to convert your input data into the server-side type you specify.
Marker[] Markers
如果您愿意,您也可以接受一个数组,例如。ASMX ScriptServices 使用的解串器 (JavaScriptSerializer) 非常灵活,并且会尽其所能将您的输入数据转换为您指定的服务器端类型。
回答by Felix Kling
markers
is not a JSON object. It is a normal JavaScript object.- Read about the
data:
option:Data to be sent to the server. It is converted to a query string, if not already a string.
markers
不是 JSON 对象。它是一个普通的 JavaScript 对象。- 阅读有关该
data:
选项的信息:要发送到服务器的数据。如果不是字符串,则将其转换为查询字符串。
If you want to send the data as JSON, you have to encode it first:
如果要将数据作为 JSON 发送,则必须先对其进行编码:
data: {markers: JSON.stringify(markers)}
jQuery does not convert objects or arrays to JSON automatically.
jQuery 不会自动将对象或数组转换为 JSON。
But I assume the error message comes from interpreting the response of the service. The text you send back is not JSON. JSON strings have to be enclosed in double quotes. So you'd have to do:
但我假设错误消息来自解释服务的响应。您发回的文本不是 JSON。JSON 字符串必须用双引号括起来。所以你必须这样做:
return "\"received markers\"";
I'm not sure if your actual problem is sending or receiving the data.
我不确定您的实际问题是发送还是接收数据。
回答by Usha
I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentTypeis set to "application/json"
. Once I removed this line everything worked great.
我尝试了 Dave Ward 的解决方案。由于contentType设置为 ,因此数据部分未在 post 请求的有效负载部分中从浏览器发送"application/json"
。一旦我删除了这条线,一切都很好。
var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }];
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ Markers: markers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
回答by Clare Panganoron
I have encountered this one too and this is my solution.
我也遇到过这个,这是我的解决方案。
If you are encountering an invalid json object exception when parsing data, even though you know that your json string is correct, stringify the data you received in your ajax code before parsing it to JSON:
如果您在解析数据时遇到无效的 json 对象异常,即使您知道您的 json 字符串是正确的,请在将其解析为 JSON 之前将您在 ajax 代码中收到的数据字符串化:
$.post(CONTEXT+"servlet/capture",{
yesTransactionId : yesTransactionId,
productOfferId : productOfferId
},
function(data){
try{
var trimData = $.trim(JSON.stringify(data));
var obj = $.parseJSON(trimData);
if(obj.success == 'true'){
//some codes ...
回答by Priya B
I have query,
我有疑问,
$("#login-button").click(function(e){ alert("hiii");
var username = $("#username-field").val();
var password = $("#username-field").val();
alert(username);
alert("password" + password);
var markers = { "userName" : "admin","password" : "admin123"};
$.ajax({
type: "POST",
url: url,
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify(markers),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert("got the data"+data);},
failure: function(errMsg) {
alert(errMsg);
}
});
});
I'm posting the the login details in json and getting a string as "Success"
,but I'm not getting the response.
我在 json 中发布登录详细信息并获取字符串 as "Success"
,但我没有得到响应。
回答by Ravi Panchal
Please follow this to by ajax call to webservice of java var param = { feildName: feildValue }; JSON.stringify({data : param})
请通过ajax调用java var param = { feildName: feildValue }; JSON.stringify({数据:参数})
$.ajax({
dataType : 'json',
type : 'POST',
contentType : 'application/json',
url : '<%=request.getContextPath()%>/rest/priceGroups',
data : JSON.stringify({data : param}),
success : function(res) {
if(res.success == true){
$('#alertMessage').html('Successfully price group created.').addClass('alert alert-success fade in');
$('#alertMessage').removeClass('alert-danger alert-info');
initPriceGroupsList();
priceGroupId = 0;
resetForm();
}else{
$('#alertMessage').html(res.message).addClass('alert alert-danger fade in');
}
$('#alertMessage').alert();
window.setTimeout(function() {
$('#alertMessage').removeClass('in');
document.getElementById('message').style.display = 'none';
}, 5000);
}
});