2017-07-19 63 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:很高興幫助你擺脫這個障礙。 –