[英]No response from localhost with ajax request
function sendSong(songN) {
console.log("sendSong ran");
var tlh = new XMLHttpRequest(), url = "http://localhost/stream/musicgrabber.php";
tlh.open("POST", url, true);
tlh.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
console.log(tlh);
//output=XMLHttpRequest {statusText: "", status: 0, response: "", responseType: "", responseXML: null…}
tlh.onreadystatechange = function() { //readystate never changes.
console.log(tlh); //this doesn't fire
if(tlh.readyState == 4 && tlh.status == 200) {
var return_data = tlh.responseText;
}
tlh.send("songname="+songN); //can't tell if this is sending or not.. nothing my php file is supposed to do, happens.
};
}
javascript文件中的其他所有内容都正常,我的问题是对服务器的请求。.我正在尝试使用浏览器中运行的脚本向localhost发布POST请求(用户脚本会注入此页面(也来自// localhost
/) ,所以我知道有很多工作。
chrome中的javascript控制台未返回任何其他错误,并且我的PHP文件没有错误..下面:musicgrabber.php
$ssn = file_get_contents("http://localhost/stream/currentsong.txt");
if($ssn != $_POST['songname']) {
saveSong($_POST['songname']);
}else{
echo "You messed up, or it's the same song";
}
function saveSong ($sname){
$fo = fopen("currentsong.txt", 'w');
fwrite($fo, $sname);
fclose($fo);
$fcheck = file_get_contents("songhistory.txt");
if($fcheck){
$hday = date('\[m\/d\/ g:i a\ \] \\n');
$writeto = $sname + $hday + $fcheck;
file_put_contents($writeto);
}
}
发送带有AJAX的请求,不更新文本文件以及当我将$ _GET与.php?songname = test一起使用时,php无法运行。
网络返回304,从缓存中返回200,而我还很陌生,我不知道该如何查看是否建立了连接。
我不确定我缺少什么,但是我已经在整个过程中进行了大约12个小时的工作,因此我们将不胜感激。
====更新====
我设法使响应正常工作(-ish)。我得到“ XMLHttpRequest无法加载http:// localhost
/stream/musicgrabber.php。所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问“ //www.domainhere.com”。” 有什么办法可以绕开这个吗? 它正在通过localhost发送信息,所以不知道该如何解决。
为什么不尝试jquery post方法
function sendSong(songN){
$.post(
url: "http://127.0.0.1/stream/musicgrabber.php",
{data: "songname="+songN},
function(response){
alert(response);
});
}
找到了解决我的问题的方法..我所有的请求协议,或者形成请求的顺序都不尽人意..这是我脚本的固定部分。
function sendSong(songN) {
console.log("sendSong ran");
var tlh = new XMLHttpRequest(), url = "http://127.0.0.1/stream/musicgrabber.php";
tlh.open("POST", url, true);
tlh.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
tlh.send("songname=" + songN);
console.log(tlh);
tlh.onreadystatechange = function () {
console.log(tlh);
if (tlh.readyState == 4 && tlh.status == 200) {
console.log(tlh.responseText);
}
};
}
对于跨站点问题,我通过添加以下内容解决了该问题:
header("Access-Control-Allow-Origin: *");
到我的musicgrabber.php。 我还需要解决其他一些小问题,但是请求正在处理中,谢谢大家提供的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.