jQuery 如何将 JSON 数据发送到服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4342926/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:06:11  来源:igfitidea点击:

How can I send JSON data to server

jqueryjsonhttp-post

提问by Daniel Chen

Well, here is the story:

好吧,这是故事:

I have some data need to send to server, but they should turned into JSON dataType first.

我有一些数据需要发送到服务器,但它们应该先变成 JSON dataType。

I made such ajax call:

我做了这样的ajax调用:

    $.ajax({
       url: url, // the url I want to post to.
       type: 'POST',
       contenttype:'application/json; charset=utf-8',
       beforeSend: //some HTTP basic auth stuff
       data: {
          name:'test',
          key:'foo',
          key2:'bar'
       },
       dataType:'JSON'
});

basically I'm expecting the data I send to server was:

基本上我期待我发送到服务器的数据是:

[name:test,key:foo,key2:bar]

but what I've got was:

但我得到的是:

name=test&key=foo&key2=bar

What did I missing? How can I get those data into JSON?

我错过了什么?如何将这些数据转换为 JSON?

回答by ShiftyThomas

 var data = {'bob':'foo','paul':'dog'};
 $.ajax({
   url: url,
   type: 'POST',
   contentType:'application/json',
   data: JSON.stringify(data),
   dataType:'json'
 });

/** Added **/

/** 添加 **/

The above does not do anything with the response from the server if you need to do something then a callback will be called when the server has responded.

如果您需要执行某些操作,则上述内容不会对来自服务器的响应执行任何操作,则在服务器响应时将调用回调。

 var data = {'bob':'foo','paul':'dog'};
 $.ajax({
   url: url,
   type: 'POST',
   contentType:'application/json',
   data: JSON.stringify(data),
   dataType:'json',
   success: function(data){
     //On ajax success do this
     alert(data);
      },
   error: function(xhr, ajaxOptions, thrownError) {
      //On error do this
        if (xhr.status == 200) {

            alert(ajaxOptions);
        }
        else {
            alert(xhr.status);
            alert(thrownError);
        }
    }
 });

回答by Jonas

I've had the same problem. You can't send an object as "data", you need to stringify the object. Try this instead, with your object stringified:

我遇到了同样的问题。您不能将对象作为“数据”发送,您需要对对象进行字符串化。试试这个,用你的对象字符串化:

$.ajax({
       url: url,
       type: 'POST',
       contentType:'application/json',
       data: '{
          name:"test",
          key:"foo",
          key2:"bar"
       }',
       dataType:'json'
});

回答by Jānis Gruzis

Try this: http://www.abeautifulsite.net/blog/2008/05/postjson-for-jquery/

试试这个:http: //www.abeautifulsite.net/blog/2008/05/postjson-for-jquery/

Its a lot shorter:

它要短得多:

$.post(url, data, function(response) {
    // Do something with the response
}, 'json');

回答by Keaton Robinson

I agree the data must be converted into a JSON string, not only to agree with the dataTypeand contentTypesetup but more importantly, to satisfy the server.

我同意必须将数据转换为 JSON 字符串,不仅要同意dataTypecontentType设置,更重要的是要满足服务器。

data: JSON.stringify(data),
dataType:'json'

回答by MagePsycho

There are many ways to send JSON data to the server

有很多方法可以将 JSON 数据发送到服务器

1. Using Ajax

1. 使用 Ajax

var data = <?php echo json_encode($data) ?>;
var url  = '<?php echo $url ?>';
jQuery.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        var jsonObj = jQuery.parseJSON(data);
        alert(jsonObj.encPassword);
    },
    failure: function(errorMsg) {
        alert(errorMsg);
    }
});

2. Using Curl

2. 使用卷曲

<?php
$content = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //curl error SSL certificate problem, verify that the CA cert is OK

$result     = curl_exec($curl);
$response   = json_decode($result);
var_dump($response);
curl_close($curl);
?>

3. Using Streams

3. 使用流

<?php
$options = array(
    'http' => array(
        'method'  => 'POST',
        'content' => json_encode( $data ),
        'header'=>  "Content-Type: application/json\r\n" .
                    "Accept: application/json\r\n"
      )
);

$context     = stream_context_create($options);
$result      = file_get_contents($url, false, $context);
$response    = json_decode($result);
var_dump($response);

4. Raw HTTP Post

4. 原始 HTTP Post

Using Zend Framework's HTTP client: http://framework.zend.com/manual/en/zend.http.client.advanced.html#zend.http.client.raw_post_data

使用 Zend Framework 的 HTTP 客户端:http: //framework.zend.com/manual/en/zend.http.client.advanced.html#zend.http.client.raw_post_data

$json = json_encode($data);
$client = new Zend_Http_Client($url);
$client->setRawData($json, 'application/json')->request('POST');
var_dump($client->request()->getBody());

SOURCE:- https://blog.magepsycho.com/sending-json-data-remote-server/

来源:- https://blog.magepsycho.com/sending-json-data-remote-server/

回答by cmg_george

Also, is necesary can create a parameter and assign the value with JSON.stringify

此外,有必要可以创建一个参数并使用 JSON.stringify 分配值

....
data: "jsonString="+JSON.stringify(data),
...

回答by Bruce Dou

dataType: 'json',