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

时间:2010-12-03 06:07:43

标签: jquery json http-post

嗯,这是故事:

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

我做了这样的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'
});

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

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

但我得到的是:

name=test&key=foo&key2=bar

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

7 个答案:

答案 0 :(得分:22)

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

/ **添加了** /

如果您需要执行某些操作,上面的内容对服务器的响应没有任何作用,那么当服务器响应时将调用回调。

 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);
        }
    }
 });

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

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

它短得多:

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

答案 3 :(得分:0)

此外,必要时可以创建参数并使用JSON.stringify

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

答案 4 :(得分:0)

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

contentType

答案 5 :(得分:0)

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

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。使用Curl

<?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。使用流

<?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。原始HTTP发布

使用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());

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

答案 6 :(得分:-3)

dataType: 'json',
相关问题