将JSON从Javascript发送到PHP服务器

时间:2017-06-22 03:59:48

标签: javascript php jquery json

我想将jSON从javascript发送到PHP服务器,反之亦然,但是从服务器获取数据时我得到异常SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

我尝试在JSONLint上验证JSON输出,并且我的JSON有效。 以下是我希望从服务器获得的JSON:

{
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4,
    "e": 5
}

和我发送给服务器的JSON:

{"counter":"123"}

以下是我的代码:

  $.ajax({
      type: 'POST',
      url: 'http://localhost:8080/debug/json.php',
      data: {json: JSON.stringify(obj)}, 
      dataType: 'json'
  })
  .done( function( data ) {
      console.log('done');
      console.log(data);
  })
  .fail( function( data ) {
      console.log('fail');
      console.log(data);
  });

当obj是

var obj = {"counter":counter};

和服务器端(php)

<?php
    header('Content-type: application/json');
    $json = file_get_contents('php://input');
    $json_decode = json_decode($json, true); 
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); 
    echo json_encode($arr);
?>

请求标题

Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 36
Origin: null
Connection: keep-alive

响应标题

Date: Thu, 22 Jun 2017 04:11:53 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By: PHP/5.4.7
Content-Length: 31
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json

我认为问题来自我的PHP脚本,但当我尝试直接从URL访问时,它的工作就像一个魅力。我获得了状态代码200,但response error。我错过了什么?谢谢。

0 个答案:

没有答案