2016-12-02 138 views
0

我有一個API集成,SMS服務希望我們以這種格式發送數據,內容類型爲json。Jquery Ajax使用表單數據傳遞JSON數組格式

{ 
    "from": "91887654681", 
    "to": ["918757077777"], 
    "body": "Hi this is my message using Mblox SMS REST API" 
} 

我有一個形式與輸入文本即from,to和body。

這是我的表單提交方式。

$("#sendSMSForm").submit(function(event){ 
    event.preventDefault(); 
    // Serialize the form data. 
    var form = $('#sendSMSForm'); 
    var formData = $(form).serialize(); 
    //alert(formData); 
    $.ajax({ 
     type: 'POST', 
     dataType: 'json', 
     contentType: "application/json", 
     url: $(form).attr('action'), 
     data: formData 
    }).done(function(response) { 
     // Do some UI action stuff 
     alert(response); 
    }); 
}); 

我不知道......應該用什麼來傳遞一個類似的格式......其中「to」是一個數組。

+1

如果你在客戶端jQuery中進行這種集成,有人會運行你的SMS帳單。在PHP中處理這個服務器端。爲什麼用PHP標記呢? – WEBjuju

回答

3

只要讓你的輸入字段to陣列

<input type="number" name="to[]" value="918757077777"/> 
<input type="number" name="to[]" value="918757077778"/> 
<input type="number" name="to[]" value="918757077779"/> 
+0

是的。那就對了。你可以肯定地考慮這個答案。 – Perumal

+0

@VishalKumar嘗試https://plugins.jquery.com/serializeJSON/ – Justinas

0

@ WEBjuju的評論是非常有幫助的....爲什麼要在客戶端做這樣的集成...它真的是一個新手和壞習慣。最後,我在服務器端管理這個...使用PHP創建這樣的json。以下是可以幫助某人的示例。這是一個使用cURL進行HTTP REST調用的PHP函數。

function callAPI($to, $body) 
{ 
try{ 
// I am creating an array of Whatever structure I need to pass to API 
$post_data = array('from' => ''.$this->from.'', 
'to' => array(''.$to.''), 
'body' => ''.$body.''); 

//Set the Authorization header here... most APIs ask for this 
$curl = curl_init(); 
$headers = array(
'Content-Type: application/json', 
'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXX' 
); 
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 

//If you have basic authorization, next 3 lines are required 
$username ="venturecar15"; 
$password = "voaKmtWv"; 
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password); 

//Not receommended but worked for me 
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 

curl_setopt($curl, CURLOPT_URL, $this->ApiURL); 
curl_setopt($curl, CURLOPT_POST, true); 
//This is how we can convert an array to json  
$test = json_encode($post_data); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $test); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
$result = curl_exec($curl); 
} catch(Exception $e) { 
    return "Exception: ".$e->getCode()." ".$e->getMessage(); 
} 

if($result === FALSE) { 
    $error = curl_error($curl)." ".curl_errno($curl); 
    return "Error executing curl : ".$error; 
} 
curl_close($curl); 
return "SMS sent successfully to ".$to."."; 
}