本地主机对ajax请求没有响应


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文件的其他一切工作,我的问题是请求服务器..我试图发布一个post请求到本地主机的脚本在我的浏览器中运行(userscript注入这个页面(也从//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);
    }
}

php不运行时,请求与AJAX发送,文本文件不更新,当我使用$_GET与.php?Songname =test it works.

网络返回304,从缓存中使用200,我仍然是相当新的,我不知道如何查看连接是否正在进行。

我不知道我错过了什么,但我已经在整个事情上工作了大约12个小时,所以任何和所有的帮助都是非常感激的。

====更新====

我设法使响应工作(-ish)..我得到"XMLHttpRequest无法加载http://localhost/stream/musicgrabber.php。请求的资源上没有'Access-Control-Allow-Origin'标头。因此,Origin '//www.domainhere.com'是不允许访问的。它通过本地主机发送信息,所以不知道该怎么做来修复它。

为什么不试试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。还有一些小事我需要解决,但是请求正在处理中,谢谢大家提供的帮助。