繁体   English   中英

Ajax,从单个js调用多个PHP函数

[英]Ajax, call multiple PHP function from a single js

我的项目有问题。 在我的网站中,我有一个带有单个按钮的页面html和onclick()eventa js函数调用intro.js,通过XmlHttpRequestObject必须在许多php函数中进行多次调用,详细信息:

在js我调用scan()函数

function scan() {
 if (xmlHttp)
 {
 // try to connect to the server
 try
 {
  // initiate reading the async.txt file from the server
  xmlHttp.open("GET", "php/intro.php?P1=http://"+oStxt.value, true);
  xmlHttp.onreadystatechange = handleRequestStateChange;
  xmlHttp.send(null);
  // change cursor to "busy" hourglass icon
  document.body.style.cursor = "wait";    
}
// display the error in case of failure
catch (e)
{
  alert("Can't connect to server:\n" + e.toString());
  // revert "busy" hourglass icon to normal cursor
   document.body.style.cursor = "default";
}
}

}

在handleRequestStatuschange我有:

function handleRequestStateChange()
 {
 // obtain a reference to the <div> element on the page
 // display the status of the request 
 if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
 {
 // revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
// read response only if HTTP status is "OK"
if (xmlHttp.status == 200) 
{
  try
  {
    // read the message from the server
    response = xmlHttp.responseText;
    // display the message 
document.body.appendChild(oRtag);
oPch = document.getElementById("divRtag");
oOch = document.createTextNode(response);
oPch.appendChild(oOch);
  }
  catch(e)
  {
    // display error message
    alert("Error reading the response: " + e.toString());
  }
} 
else
{
    // display status message
  alert("There was a problem retrieving the data:\n" + 
        xmlHttp.statusText);
  // revert "busy" hourglass icon to normal cursor
  document.body.style.cursor = "default"; 
}
}
}

它适用于一个php调用,但我需要在intro.php(scan2.php,scan3.php,ecc ecc)之后调用扫描函数中的不同php页面,并使用json_decode写入在div标签中返回的数组的单个数据我的HTML页面。 哪个是调用不同php页面并使用ajax中的单个js函数管理结果的最佳方法?

在此先感谢亚历山德罗

不确定你是如何构建你的php函数的。 你不能创建一个调用其他功能(扫描)的功能吗?

function doScan(){

  $data = array();

 //like this, or with a loop
 $data['scan1'] = scan1();
 ....
 $data['scanN'] = scanN();

echo json_encode($data);

}

真的,想到的最简单的方法就是参数化这个功能。 这很简单

function doScan(url) { // Code here }

然后使用url变量简单地创建完全相同的ajax请求。

xmlHttp.open("GET", "php/" + url + "?P1=http://"+oStxt.value, true);

接下来,只需使用各种参数调用doScan函数。

doScan("index.php");
doScan("otherPage.php");
doScan("somethingElse.php");

这将在您指定的PHP文件上发出ajax请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM