Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - 无法使用XMLHttpRequest()将外部file.js的数据发送到php(Failed to Send data with external file.js to php using XMLHttpRequest())

put the javascript code directly in the HTML page, it does work.(将JavaScript代码直接放在HTML页面中,即可正常工作。)

Howcome it does not work if I reference the script using the src attribute on the script This is my HTML page:(如果我使用脚本上的src属性引用该脚本,它将无法正常工作,这是我的HTML页面:)
<html>
  <head></head>
  <body>
    <script src="file.js"></script>
  </body>
</html>

I can not get the following javascript code to send data to a PHP page: this is inside file.js(我无法获得以下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);

and this is inside server.php :(这是在server.php内部:)

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

When I put the javascript code directly in the HTML page, it does work.(当我将javascript代码直接放在HTML页面中时,它确实起作用。)

Howcome it does not work if I reference the script using the src attribute on the script tag?(如果我使用script标记上的src属性引用脚本,怎么办?) for example when i put the file.js script in online compiler like 'playcode.io' it does not work(例如,当我将file.js脚本放在“ playcode.io”之类的在线编译器中时,它不起作用)   ask by MYARCH translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't matter whether you put the javascript code directly in the HTML page or add it to the script using the src attribute on the script.(可以直接将javascript代码放在HTML页面中,也可以使用脚本上的src属性将其添加到脚本中。)

The problem is, you aren't setting a request header with setRequestHeader() .(问题是,您没有使用setRequestHeader()设置请求标头。) Add the following line of code just after http.open() , but before http.send() and it'll definitely work:(在http.open()之后但在http.send()之前添加以下代码,它肯定会起作用:)
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

The application/x-www-form-urlencoded format provides a way to encode name-value pairs.(application/x-www-form-urlencoded格式提供了一种编码名称-值对的方式。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...