我想在没有页面重新加载和重定向的情况下发送短信,但是如果没有重定向到操作页面,表单就无法正常工作。这是我的代码。
包含表单的页面
<div class="blog">
<form method="post">
<input type="hidden" name="message" value="whatever">
<input type="text" name="tono" maxlength="10">
<input type="submit" value="SEND SMS" id="sendit">
</form>
<script>
$(document).ready(function(){
$("#sendit").click(function(){
$.ajax({
type: "POST",
url: "./example.php",
data: $(form).serialize();
}).done(function(response) {
alert(response);
});
return false;
});
});
</script>
</div>
使用example.php
<?php
error_reporting(E_ALL);
ob_implicit_flush(true);
include_once "class.curl.php";
include_once "class.sms.php";
include_once "cprint.php";
$smsapp=new sms();
$smsapp->setGateway('way2sms');
$myno='XXXXXXX';
$p='XXXXXXXX';
$tonum=$_POST['tono'];
$mess=$_POST['message'];
cprint("Logging in ..\n");
$ret=$smsapp->login($myno,$p);
if (!$ret) {
cprint("Error Logging In");
exit(1);
}
print("Logged in Successfully\n");
print("Sending SMS ..\n");
$ret=$smsapp->send($tonum,$mess);
if (!$ret) {
print("Error in sending message");
exit(1);
}
print("Message sent");
?>
这会重新加载页面但不提交表单,如果我添加action属性,它会重定向到example.php并成功发送短信。
答案 0 :(得分:2)
我看到你在处理程序中返回false,这与使用event.preventDefault()
基本相同,但这不起作用,因为你有语法错误(不应该有分号):
$(document).ready(function () {
$("#sendit").click(function () {
$.ajax({
type: "POST",
url: "./example.php",
data: $(form).serialize() // You have ";" here, and it's causing the rest of the code to fail.
}).done(function (response) {
alert(response);
});
return false;
});
});