【问题标题】:How can I send JSON data to server如何将 JSON 数据发送到服务器
【发布时间】:2010-12-03 06:07:43
【问题描述】:

好吧,故事是这样的:

我有一些数据需要发送到服务器,但它们应该先转换为 JSON 数据类型。

我做了这样的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?

【问题讨论】:

标签: jquery json http-post


【解决方案1】:
 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);
        }
    }
 });

【讨论】:

  • 这篇文章有回应吗?或者也许是一个更好的问题,有没有办法在不处理回复的情况下发帖?有点像只有一个数据包的流
  • 这不处理任何从服务器返回的响应。
  • 谢谢,如果我只想发送带有一些数据的请求,那么 $.post 会更好;不关心回报?
  • $.post 只是 $.ajax (api.jquery.com/jquery.post) 的缩短版本,因此“更好”的 $.post 也没有返回数据的回调函数。我喜欢使用 $.ajax 只是因为我一直都有。
【解决方案2】:

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

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

【讨论】:

  • 我也见过这个,但我见过这样的例子:data: {name: 'test', key: 'foo', key2: 'bar'}。每次我尝试这样编码时它都会失败
【解决方案3】:

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

它要短得多:

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

【讨论】:

  • 我喜欢这种方式。 $.ajax 更适合低级别。
  • 链接已失效,但当前版本的 jQuery 在任何情况下都提供了等价物,并提供了一些错误处理技巧:请参阅 the API documentation
【解决方案4】:

另外,有必要可以创建一个参数并用 JSON.stringify 赋值

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

【讨论】:

    【解决方案5】:

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

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

    【讨论】:

      【解决方案6】:

      向服务器发送 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。使用卷曲

      <?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/

      【讨论】:

        【解决方案7】:
        dataType: 'json',
        

        【讨论】:

        • 更清楚地说,这个答案意味着您错误地将dataType 值大写。字符串比较区分大小写,jQuery 只测试"json",而不是"JSON"
        • dataType 用于响应返回的数据,而不是用于发布。
        猜你喜欢
        • 2013-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        • 2016-06-12
        • 1970-01-01
        相关资源
        最近更新 更多