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文件中的其他所有内容都可以正常工作,我的问题出在服务器请求上。我正在尝试使用浏览器中运行的脚本将POST请求发布到本地主机(用户脚本会注入此页面(也来自// localhost
/),因此,我知道有很多工作要做。)该连接是我在某个地方找到的修改后的代码段,并更改了我的信息。
chrome中的javascript控制台未返回其他错误,并且我的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'标头。Origin' //www.domainhere.com'因此不被允许访问。” 有什么办法可以绕过这个吗?它正在通过localhost发送信息,所以不知道要怎么解决。
找到了解决我的问题的方法..我所有的请求协议,或者形成请求的顺序都不尽人意..这是我脚本的固定部分。
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。我还需要解决其他一些小问题,但是请求正在处理中,谢谢大家提供的帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句