通过嵌套对象的jQuery阿贾克斯嵌套、对象、阿贾克斯、jQuery

2023-09-10 17:51:33 作者:难拥

我想通过以下使用jQuery的阿贾克斯嵌套的对象:

I want to pass following nested object in ajax using jquery:

{
   "parent_param1" : [
      {
         "sub_param1" : "sub_val1",
         "sub_param2" : "sub_val2"
      },
      {
         "sub_param1" : "sub_val1",
         "sub_param2" : "sub_val2"
      },
      {
         "sub_param1" : "sub_val1",
         "sub_param2" : "sub_val2"
      }
   ],
   "parent_param2" : "par_val2",
   "parent_param3" : "par_val3"
}

我想通过它像下面的例子:

I'm trying to pass it like following example:

var url = encodedURL;
var data = 'Above Object';

$.ajax({            
    type:'POST',
    url:url,
    dataType:'json',
    data:data,
        success:function(res){                      
              alert('success');                         
    },
    error:function(e){
      alert('error');   
    }                   
});

我收到运行时错误作为响应。我想确保已使用jQuery通过嵌套对象AJAX的正确方法是什么?

I'm getting runtime error as response. I want to make sure that Is that correct way to pass nested object in AJAX using jQuery?

推荐答案

现在你只是传递一个对象到服务器,没有钥匙。您需要将数据作为JSON字符串。

Right now you are just passing an object to the server, without a key. You need to pass the data as a JSON string.

console.log(typeof data); //object
console.log(typeof JSON.stringify(data)); //string

为了读取数据的服务器端,你需要传递的数据作为对象常量一个键和一个值。事情是这样的:

In order to read the data serverside, you need to pass the data as an object literal with a key and a value. Something like this:

data: { dto: JSON.stringify(data) },

在服务器端,您可以访问对象以不同的方式,根据不同的语言。

On the serverside, you can access the object in different ways, depending on the language.

PHP:

$dto = $_POST['dto'];

ASP.NET:

ASP.NET:

var dto = HttpContext.Current.Request.Form['dto'];