无效的JSON原语:id

我无法使以下function正常工作。 它似乎是错误的序列化。 这是关于不同数据变体的第5次迭代。 我最初只是在做数据:{‘id’:id}就像我在使用WCF一样,但是使用ASMX它只是不起作用。 它看起来像是将数据序列化为id = 1234而不是id:1234,但我对此很新。 任何帮助,将不胜感激。 哦,我可以直接在浏览器中调用服务,它会正确返回数据,所以我知道它不是服务。

function getVentID(id) { //look up id in database and get VentID alert('id: ' + id); var jsdata = { "id": + id} $.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', url: 'services/UserService.asmx/getVentID', data: jsdata, dataType: 'json', success: function (msg) { alert(msg.d); }, error: function (a, b, c) { alert('Error: ' + a.toString() + ' ' + b.toString() + " " + c.toString()); } }); } 

ps我知道有10个相同的问题,但没有一个我能找到或者对我有用的答案。

最简单的修复方法是将var jsdata开头的行更改为:

 var jsdata = '{id:' + id + '}'; 

问题是jQuery将jsdata编码为表单数据,而不是json。 dataType参数影响解析响应的方式,而不影响POST数据的编码方式。

据我所知,jQuery中实际上没有任何JSON序列化代码。 显然John Resig建议使用Douglas Crockford的json2.js 。

要使用它,请向json.js添加脚本引用,然后:

 var jstext = JSON.stringify(jsdata, null, 2); 

我现在解决了这个问题。

您需要以这种格式传递url:

http://domain.com.br/service.asmx/method?objParam= {q:“search”}

在service.asmx文件中,您需要声明此方法:

 Public Function method(objParam As Dictionary(Of String, String)) End Function 

在您的代码中,看起来像:

 function getVentID(id) { var jsdata = { "id": +id } var sData = JSON.stringify(jsdata); //convert your json in string $.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', url: 'services/UserService.asmx/getVentID', data: { id: sData }, dataType: 'json', success: function(msg) { alert(msg.d); }, error: function(a, b, c) { alert('Error: ' + a.toString() + ' ' + b.toString() + " " + c.toString()); } }); }