2017-07-19 62 views
2

我正在使用jQuery和php发布数据到服务器的数据。Ajax发布json服务使用php

这是客户端代码:

var serverService="http://localhost/service/"; 
var base_url = serverService+'doing.php'; 
     $.ajax({ 
      type: "POST", 
      url: base_url, 
      dataType: "json", 
      contentType: "application/json", 
      data: JSON.stringify({ 
       "user": "test", 
       "type": "type 1" 
      }), 
      crossDomain: true, 
      cache: false, 
      success:function(data) 
      { 
       console.log(data); 
      }, 
      error: function(e) { 
       console.log(e); 
      } 
     }); 

这是服务器:

$data = json_decode(file_get_contents('php://input'), true); 
$result = array(); 
if(isset($data['user']) && isset($data['type'])){ 
    //do something 
} 
else{ 
    $result['error'] = "fail"; 
} 
echo json_encode($result, JSON_UNESCAPED_UNICODE); 

发布时,服务器无法识别用户和类型,表明它的回报荃fail

请帮帮我!

+0

什么是serverService在这里? –

+0

'var serverService =“http:// localhost/service /”'我包含index.js,它工作是因为它返回'$ result'。但我会编辑我的帖子。 tks –

回答

1

您需要添加数据,如下所述。

FROM

data: JSON.stringify({ 
       "user": "test", 
       "type": "type 1" 
      }), 

TO

data: JSON.stringify({ 
       user: "test", 
       type: "type 1" 
      }), 

让我知道,如果它不工作。

+0

是的,这是工作,〜^^〜,我的错,它太疯狂了^^,谢谢! –

+0

@CaoHữuThànhHuy:很高兴帮助你摆脱这个障碍。 –