繁体   English   中英

无法使用 XMLHttpRequest() 将带有外部 file.js 的数据发送到 php

[英]Failed to Send data with external file.js to php using XMLHttpRequest()

将 javascript 代码直接放在 HTML 页面中,它确实有效。 如果我使用脚本上的 src 属性引用脚本,它怎么会不起作用这是我的 HTML 页面:

<html>
  <head></head>
  <body>
    <script src="file.js"></script>
  </body>
</html>

我无法获得以下 javascript 代码来将数据发送到 PHP 页面:这是在 file.js 中

var http = new XMLHttpRequest();
var url = 'server.php';
var params = 'a=use&b=12345678';
http.open('POST', url, true); // error javascript stop always here
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) 
{ alert(http.responseText); } }
http.send(params);

这是在server.php里面:

<?php
$username = $_POST['a'];
$password = $_POST['b'];
echo 'username :' . $username;
?>

当我将 javascript 代码直接放在 HTML 页面中时,它确实有效。 如果我使用script标签上的src属性引用脚本,它为什么不起作用? 例如,当我将 file.js 脚本放在像“playcode.io”这样的在线编译器中时,它不起作用

将 javascript 代码直接放在 HTML 页面中或使用脚本上的 src 属性将其添加到脚本中都没有关系。 问题是,您没有使用setRequestHeader()设置请求 header 。 http.open()之后,但在http.send()之前添加以下代码行,它肯定会工作:

http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

application/x-www-form-urlencoded格式提供了一种对名称-值对进行编码的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM