【问题标题】:How to send a form with php / ajax without opening a new page when send发送时如何使用php / ajax发送表单而不打开新页面
【发布时间】:2016-04-19 10:28:38
【问题描述】:

我有一个小表单,如果表单已发送或出现问题,我会尝试返回 ajax 错误。

在connection.php中我有一个提交表单的小脚本

if($_POST['postForm'] == 'newsletter'){

    $newsletterSubscriber = new NewsletterSubscriber();
    $newsletterSubscriber->set('CMS_newsletters_id', 2);
    $newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
    $newsletterSubscriber->set('firstName', $_POST['voornaam']);
    $newsletterSubscriber->set('lastName', $_POST['achternaam']);
    $newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
    $newsletterSubscriber->set('emailAddress', $_POST['email']);
    $newsletterSubscriber->set('subscribed', 1);
    $saved = $newsletterSubscriber->save();

    $response = array('error_code'=>0, 
                      'message'=>'subscriber added'
                     );
    echo json_encode($response);
    exit;
}

在我的 scripts.js 中有我的 ajax:

$.ajax({
    type: "POST",
    url: "connection.php",
    data: {param1: 'aaa'},
    dataType: JSON
})
.done( function(data){
        if(data.error_code == 0) {
           alert(data.message);
        }
    }
});

我收到的错误是:

SyntaxError: Unexpected token '}'. Expected ')' to end a argument list.

谁能看出我做错了什么?

【问题讨论】:

  • scripts.js 代码中的括号不匹配。看看done

标签: javascript php jquery ajax forms


【解决方案1】:

您的 JavaScript 代码有错误:

$.ajax({
    type: "POST",
    url: "connection.php",
    data: {param1: 'aaa'},
    dataType: JSON
})
.done( function(data){
        if(data.error_code == 0) {
           alert(data.message);
        }
//You had an extra } here.
});

【讨论】:

  • 谢谢!但是当我提交它时,它现在进入一个 blanco 页面:{“error_code”:0,“message”:“subscriber added”}
【解决方案2】:

尝试以下操作:将 done 替换为 jquery ajax 的成功属性

$.ajax({
    type: "POST",
    url: "connection.php",
    data: {param1: 'aaa'},
    dataType: JSON,
    success:function(data){
      if(data.error_code == 0) {
           alert(data.message);
        }
    }
});

【讨论】:

  • @RuchishParikh .done 成功回调选项的替代构造,.done() 方法替换了已弃用的 jqXHR.success() 方法。实现细节参考 deferred.done()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多