在表单提交上使用以下Ajax POST函数(这里简化了):
$form.on("submit", function (i) {
i.preventDefault();
var sendEmail = 1;
ValidateForm(sendEmail, "goSignup");
});
function ValidateForm(sendEmail, action) {
$.ajax({
type: "POST",
url: window.location.pathname,
dataType: "json",
data: {
ajaxRequest: 1,
sendEmail: sendEmail,
}
}
我发布后,我想使用一个条件GET参数等于1(即https://www.example.com?test-parameter=1),然后,如果它存在于URL使用一个或另一个函数从那里,如果ajaxRequest从$_POST在我的PHP收到:
public function __construct() {
$testingParameter = $_GET["test-parameter"] ?? '';
if (trim($testingParameter) == '1') { // if has get parameter equal
if (!empty($_POST['ajaxRequest'])) { // if JS postRequest has been posted
$this->handlePostRequests();
}
echo 'has get parameter';
} else { // else use old logic
if (!empty($_POST['ajaxRequest'])) {
$this->handleOtherRequests();
}
echo 'no get parameter';
}
}
问题:我从PHP得到正确的回声,但当我提交表单与Ajax它仍然使用handleOtherRequests();
而不是handlePostRequests();
函数,如果我使用url www.example.com?test-parameter=1.
这里可能有一些基本的PHP逻辑错误,如果有人能在正确的方向上指导我,我将不胜感激。
url: window.location.pathname,
您的Ajax永远不会将数据POST到带有查询字符串的URL,因为您显式地只接受路径名。
也许你想要location.href
。