我目前正在使用短信服務twilio向用戶發送具體信息。表單在提交時使用操作和提交方式提交時提交併提交。我想將其更改爲AJAX提交的表單。請有任何想法嗎?我有以下一些代碼,它目前是如何工作的:將PHP聯繫表格轉換爲AJAX
****聯繫形式****
<form action="sendsms.php" method="post" id="sms">
<input type="text" name="name" id="name" value="Sam"/>
<input type="phone" name="phone" id="phone" value="0000000000"/>
<textarea name="message" style="width: 500px; height: 300px;"> Test Message</textarea>
<input type='submit' value='submit'/>
</form>
**** **** PHP
<?php
if($_POST)
{
require "Services/Twilio.php";
$AccountSid = "ACaa1c********";
$AuthToken = "ae6c269********";
$client = new Services_Twilio($AccountSid, $AuthToken);
$from = '+44**********';
$name = $_POST['name'];
$phone = $_POST['phone'];
// Send a new outgoing SMS */
$body = htmlspecialchars($_POST['message'].$name);
$client->account->sms_messages->create($from, $phone, $body);
echo "Sent message to $name";
}
?>
**** **** AJAX
$('#sms').submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
//get input field values
var user_name = $('input[name=name]').val();
var user_phone = $('input[name=phone]').val();
var user_message = $('textarea[name=message]').val();
var proceed = true;
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userPhone':user_phone, 'userMessage':user_message};
//Ajax post data to server
$.post('sendsms.php', post_data, function(data){
alert(data);
}).fail(function(err) { //load any error data
$("body").hide().html('<div class="error">'+err.statusText+'</div>').slideDown();
});
}
return true;
});
表單或PHP上的任何內容都無法更改,只需在它們之間添加AJAX組件即可。在網上有*卡車加載*的AJAX教程。 – 2014-11-05 13:17:40
嗨周杰倫,我已經嘗試了一個AJAX嘖嘖迄今,我不斷收到失敗的消息。我可以問如果我爲每個值創建$ _POST的變量,該變量是否需要在AJAX腳本中的名稱與它在php腳本中的名稱相同? – 2014-11-05 13:20:47
發佈您在此嘗試的AJAX @SamCrowe。另外,在測試時打開瀏覽器的控制檯,查看正在發送和接收的內容。 – 2014-11-05 13:25:28