【问题标题】:Form not submitting without redirecting表单不提交而不重定向
【发布时间】:2015-11-04 19:22:53
【问题描述】:

我想在没有页面重新加载和重定向的情况下在点击时发送短信,但是如果没有重定向到操作页面,表单就无法工作。这是我的代码。

包含表单的页面

<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");

?>

这会重新加载页面但不提交表单,如果我向表单添加操作属性,它会重定向到 example.php 并成功发送短信。

【问题讨论】:

  • 使用 even,preventDefault() 来停止重新加载
  • 这不是问题,他在处理程序中返回 false。问题是语法错误。

标签: php jquery ajax forms sms


【解决方案1】:

我看到您在处理程序中返回 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;
    });
});

【讨论】:

  • 好收获!我完全错过了。代码缩进在这里确实有帮助。
  • 但在更正语法错误后,它现在也无法正常工作。不发送任何短信。如果我在表单中添加动作动作属性并且它重定向到动作页面,它会发送短信。
猜你喜欢
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2020-07-14
  • 2016-10-05
  • 2020-02-18
  • 1970-01-01
相关资源
最近更新 更多