2015-10-19 123 views
0

我对jquery ajax数据格式有疑问。从客户端传输到服务器时,用户数据的数据类型是什么? 。如果数据传递的是数据:{//用户数据}给出500个错误。但是如果像数据一样传递:“{}”或数据:“{}”,则结果为成功。我是否需要在“'或”“之间包含数据?jquery ajax发布数据查询

$.ajax({ 
       type: "POST", 
       url: "Contact.aspx/add", 
       dataType: "json", 
       data: '{ "Data": "hii" }', 
       contentType: "application/json; charset=utf-8", 
       success: function (response) { 

       }, 

       error: function (msg) { 
        alert(msg.status); 
       } 
      }); 
     ------c#------- 
     [WebMethod] 
    public static void add(string Data) 
    { 
    } 
+0

'500'表示服务器出现错误,可能是服务器期待JSON格式的数据 – Tushar

+0

在您的Web方法中使用Request.Form [“Data”]。而不是使用字符串数据参数 –

回答

0

您需要使用JSON.stringify来将obj数据串联起来。

var jsonData = JSON.stringify({ "Data": "hii" }); 
$.ajax({ 
        type: "POST", 
        url: "Contact.aspx/add", 
        dataType: "json", 
        data: jsonData, 
        contentType: "application/json; charset=utf-8", 
        success: function (response) { 

        }, 

        error: function (msg) { 
         alert(msg.status); 
        } 
       }); 
      ------c#------- 
      [WebMethod] 
     public static void add(string Data) 
     { 
     } 
+0

,但我可以使用http post方法,如下面的$ .post(“Contact.aspx/add”,{'Data':''+ JSON.stringify(arr)+''},function(result ){}); 。这里不需要任何单引号或双引号。当比较两个post方法让我迷惑 – nichu09

+0

请参阅http://stackoverflow.com/a/3870116/2074346的答案,你可以看到差异。 –

0

,你可以做这样的:

$阿贾克斯({ 类型: “POST”, 网址: “Contact.aspx /添加”, 数据类型: “JSON”, 数据:{ 数据:“hii”, }, success:function(response){ }, });

希望它有帮助。