AJAX在从iOS提交时未触发PHP邮件发送器。

huangapple go评论129阅读模式
英文:

AJAX is not triggering PHP mailer when submitting from iOS

问题

dataString = 'param=stuff';
jQuery.ajax({
   cache: false,
   type: "POST",
   headers: { "cache-control": "no-cache" },
   url: "https://example.com/assets/mailer.php",
   data: dataString, 
   success: window.location.href = "https://example.com/thankyou"
});
英文:
dataString = 'param=stuff';
jQuery.ajax({
   cache: false,
   type: "POST",
   headers: { "cache-control": "no-cache" },
   url: "https://example.com/assets/mailer.php",
   data: dataString, 
   success: window.location.href = "https://example.com/thankyou"
});

This works fine with various browsers on Windows, MacOS, and Android. On iOS, the PHP mailer script isn't triggered, but the redirect works. Using Safari dev tools I can see there aren't any errors in the console. What am I missing?

答案1

得分: 1

success接受一个函数,您同时将一个字符串传递给它,并将该字符串分配给window.location.href,然后导航离开。

改用函数代替...

jQuery
  .post("https://example.com/assets/mailer.php", { param: "stuff" })
  .done(() => {
    window.location.href = "https://example.com/thankyou";
  });

请注意,我已删除了您设置的所有多余选项,并使用更安全的方法对请求体进行编码。


FYI,您绝对不需要jQuery来实现这个

fetch("https://example.com/assets/mailer.php", {
  method: "POST",
  body: new URLSearchParams({ param: "stuff" }),
}).then((res) => {
  if (res.ok) {
    window.location.href = "https://example.com/thankyou";
  }
});
英文:

success accepts a function, you are passing it a string while simultaneously assigning that string to window.location.href and navigating away.

Use a function instead...

jQuery
  .post("https://example.com/assets/mailer.php", { param: "stuff" })
  .done(() => {
    window.location.href = "https://example.com/thankyou";
  });

Note that I've removed all the redundant options you were setting and used the safer method of encoding the request body.


FYI you definitely don't need jQuery for this

fetch("https://example.com/assets/mailer.php", {
  method: "POST",
  body: new URLSearchParams({ param: "stuff" }),
}).then((res) => {
  if (res.ok) {
    window.location.href = "https://example.com/thankyou";
  }
});

huangapple
  • 本文由 发表于 2023年3月7日 11:14:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定