2016-12-02 109 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."."; 
} 
相关问题