我目前正在使用短信服务twilio向用户发送带有详细信息的消息。表单在提交时使用动作和张贴方法进行提交和交付。我想把它改成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;
});
使用jquery直接从表单中获取动作和数据,使用attr('action')
和serialize()
:
$(function(){
$('#sms').submit(function(event) {
event.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function(data){
console.log(data); //alert(data);
}).fail(function(err){
console.log(err); //alert(err);
});
});
});
如前所述,警报是一种糟糕的调试方法。所有现代浏览器都有一个javascript控制台(谷歌chrome中的Ctrl+Shift+J,或右键单击>inspect元素以显示完整的开发工具)。console.log()
会将您的数据发送到控制台。还会显示其他javascript错误。
$(function(){
$('#sms').submit(function(e){
e.preventDefault();
var d = $(this).serialize();
$.ajax({
type : 'post',
url : 'sendsms.php',
data : d
}).done(function(data){
alert('done');
}).fail(function(x,y,z){
alert('error');
});
});
});
就这么简单。