Javascript 能够调用不同PHP页面的单个Ajax函数

Javascript 能够调用不同PHP页面的单个Ajax函数,javascript,ajax,Javascript,Ajax,我的index.html上有以下按钮: 关于我们 常见问题 联系我们试试这个,它将帮助您 函数fNt(url){ xmlhttp=新的XMLHttpRequest(); open(“GET”,url,true); xmlhttp.send(); xmlhttp.onreadystatechange=函数(){ if(xmlhttp.readyState==4&&xmlhttp.status==200){ document.getElementById(“ajax”).innerHTML=xm

我的index.html上有以下按钮:

关于我们
常见问题

联系我们
试试这个,它将帮助您

函数fNt(url){
xmlhttp=新的XMLHttpRequest();
open(“GET”,url,true);
xmlhttp.send();
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById(“ajax”).innerHTML=xmlhttp.responseText;
}
}
}
关于我们
常见问题

ContactUs
无论如何,您必须为每个按钮创建一个单独的回调(除非您希望单击每个按钮来执行完全相同的操作)。为什么不将统一的ajax代码放在一个函数中,并向该函数传递一个url和一个单独的回调函数呢。如果要检查请求对象状态,只需将其直接传递给回调:

function doGet(route, callback){
    var xhr = new XMLHttpRequest(),
        method = "GET",
        url = route; //If you need to massage the route or anything

    xhr.open(method, url, true);
    xhr.onreadystatechange = callback(xhr);
    xhr.send();
}
那么就称之为:

var route = "routedesired.com";
var callback = function(xhrObj){
   if (xhrObj.readyState == 4 && xhrObj.status == 200{
       console.log("HELLO WORLD")
   }
}
<button onClick="doGet('about_us.php')">About Us</button>
<button onClick="doGet('faq.php')">FAQ</button>
<button onClick="doGet('contact_us.php')">Contact Us</button>
另一种方法

我不知道您到底想做什么,但是如果您想为每个链接做一些不同的事情,您可以将路由添加到回调函数中,也可以添加到我创建的
doGet
函数中:

function doGet(route){

    var xhr = new XMLHttpRequest(),
        method = "GET",
        url = route; //if you need to massage the route or anything

    var callback = function(routeParam){
       if (xhr.readyState == 4 && xhr.status == 200{
           switch(routeParam){
              case "faq.php":{
                 //do some action if route is "faq.php"
              }
              break;
              //continue with the same logic for other URL's
           }
        }
    }

    xhr.open(method, url, true);
    xhr.onreadystatechange = callback(route);
    xhr.send();
}
那么就称之为:

var route = "routedesired.com";
var callback = function(xhrObj){
   if (xhrObj.readyState == 4 && xhrObj.status == 200{
       console.log("HELLO WORLD")
   }
}
<button onClick="doGet('about_us.php')">About Us</button>
<button onClick="doGet('faq.php')">FAQ</button>
<button onClick="doGet('contact_us.php')">Contact Us</button>
关于我们
常见问题
联系我们

归根结底,有不同的方法来组织它,以自动化流程并减少所需的代码量。你如何处理它的一部分取决于你在请求成功后计划做什么。

请参阅我的答案。您刚刚在
if
条件中错过了
。请使用浏览器控制台检查错误。