javascript - jQuery 和 Ajax 组合困惑

标签 javascript php jquery ajax json

我是新用户,我需要有关 JQuery 和 Ajax 的帮助。我只擅长 PHP。

我有一个 HTML 页面,其中有新闻通讯注册部分,

<h4>Newsletter</h4> 
<form id="main-news-contact-form" class="news-contact-form" name="news-contact-form" method="post" action="/scripts/xnews.php" role="form"> 
    <div class="input-group">
        <input type="text" class="form-control" required="required" placeholder="Enter your email" name="email"/> 
        <span class="input-group-btn">
            <button class="btn btn-danger" type="submit">Go!</button>
         </span>
    </div>
</form> 

以及相关的 JQuery -

//newsletter form
var form = $('.news-contact-form');
form.submit(function () {
  $this = $(this);
  $.post($(this).attr('action'), function(data) {
  $this.prev().text(data.message).fadeIn().delay(15000).fadeOut();
  },'json');
  return false;
});

我有一个 PHP 脚本,它读取表单数据并将收到的电子邮件地址保存在数据库表中,但由于某种原因,PHP 代码没有接收到数据(电子邮件地址),因此执行下面的代码。

if(empty($_POST["email"]))
{
  echo("failed");
}

我不知道我做错了什么,我有一个“联系我们”表单,它工作得非常好,但我不知道为什么这个时事通讯表单不能与 jquery 一起使用。

我保证所有的javascript文件都包含在html页面中,php页面运行得绝对正常,它不会返回任何php或mysql错误,我正确设置了JSON header ,只是我没有得到表格中输入的电子邮件地址。早些时候它可以工作,但 Ajax 无法工作,现在我设法让 Ajax 工作,但 JavaScript 代码没有发送表单数据。

你能帮我调试一下吗?

提前致谢!

最佳答案

您的代码没有向服务器发送任何数据。尝试将数据作为第二个参数添加到函数中。

// get the text from the input field with the id "email"
var email = $.("#email").val();
// get the url from the form
var url = $("#newsletter-send").attr('action');

$.post( url, { email: email }, function( data ) {
    // The code that you want to execute after sending the ajax call
}, "json");

请不要复制粘贴代码,而是尝试找出其背后的原因。您可能需要检查 url 变量以确保您发布到正确的位置。还可以尝试将 id 属性添加到包含电子邮件的输入字段。 我希望这会对您有所帮助。

关于javascript - jQuery 和 Ajax 组合困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25229846/

相关文章:

javascript - Angular/Laravel CORS 问题 : The Same Origin Policy disallows reading the remote resource

php - php 和 codeigniter 中的主要类别 + 3 级子类别

javascript - 通过单击另一个 div 更改 div 中的数据

javascript - 如何访问 NuxtJs 存储中的 localStorage?

javascript - 如何用Javascript删除HTML代码?

javascript - 服务调用后的 angularjs 表单操作

javascript - Array.push() 使所有元素在推送对象时都相同

php - 从两个表中选择而不重复所有值

javascript - 如何在 JavaScript 中以定义的时间间隔运行循环

jquery - 删除下拉菜单之间的间距