繁体   English   中英

在ajax中调用PHP函数,不赞成使用同步XMLHttpRequest

[英]Call PHP function in ajax, Synchronous XMLHttpRequest deprecarted

完全不 / 每个教程似乎都以一种或另一种方式过时了。 已经花费了大约30个小时来尝试提出一个简单的插入/检索脚本。 请帮忙! 一旦我看到了代码的工作原理,我便很容易弄懂它的文档。

我收到以下错误。

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

我的index.php相关数据,错误在xmlhttp.open行上。

disp_data();
function disp_data(){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "update.php?status=disp",false);

这是我的update.php相关代码。 在本教程中,应该在刷新时加载我的数据,但是空白。 我不确定为什么本教程将其设置为false,当我在w3schools阅读的文档ive似乎应该使它正确时,却无济于事。

$status = $_GET["status"];

if ($status == "disp") {
  $link = mysqli_connect("localhost", "root", "");
  mysqli_select_db($link, "checkbox");

$ res = mysqli_query($ link,“ SELECT * FROM table1”);

我的完整index.php

<div id ="disp_data"></div>

<script src="jquery-3.2.1.min.js"></script>
<script type ="text/javascript">

(function() {
  var newXHR = null;

  function sendXHR(type, url, data, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
    newXHR.send(data);

    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response); // Callback function to process the response.
      }
    };
  }

  sendXHR("GET", "update.php?status=disp", null, function(response) {
    document.getElementById("disp_data").innerHTML=newXHR.responseText;
  });

})();

</script>

</body>

我完整的update.php文件

$status = $_GET["status"];
if($status=="disp")
{
$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"checkbox");
$res = mysqli_query($link,"SELECT * FROM table1");

echo "<table>";
while($row = mysqli_fetch_array($res))
{
echo "<tr>";
echo "<td>";   echo $row["id"]; echo "</td>";
echo "<td>";  echo $row["name"];  echo "</td>";
echo "<td>";  echo $row["city"];  echo "</td>";

echo "</tr>";
}
echo "</table>";
}

您应该在async参数中使用true

像这样: xmlhttp.open("GET", "update.php?status=disp", true);

参见XMLHttpRequest.open()

您可以使用此辅助函数来创建XMLHttpRequest

适用于所有浏览器,包括IE6。

var newXHR = null;

function sendXHR(type, url, data, callback) {
  newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
  newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
  newXHR.send(data);
  newXHR.onreadystatechange = function() {
    if (this.status === 200 && this.readyState === 4) {
      callback(this.response); // Callback function to process the response.
    }
  };
}

用法:

sendXHR("GET", "update.php?status=disp", null, function(response) {
  console.log(response);
});

您可以使用此演示来检索数据:

 (function() { var newXHR = null; function sendXHR(type, url, data, callback) { newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP"); newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI. newXHR.send(data); newXHR.onreadystatechange = function() { if (this.status === 200 && this.readyState === 4) { callback(this.response); // Callback function to process the response. } }; } // Example 1: Get data. var btnRequest = document.getElementById("btnRequest"); btnRequest.onclick = function() { sendXHR("GET", "https://gist.githubusercontent.com/dannyjhonston/22851f9c21733973b2705b0b65443f90/raw/30cf99ceeb470a7ab6d2ffb51a78f1bb57f41ca3/data.txt", null, function(response) { document.getElementById("myDiv").innerHTML = response; // response contains the data from the server. }); }; // Example 2. Cancel a long request. var btnCancelRequest = document.getElementById("btnCancelRequest"); btnCancelRequest.onclick = function() { newXHR.abort(); // You can use the newXHR variable to abort a XMLHttpRequest that is taking long time to response, with the .abort() method. }; })(); 
 #myDiv { border: solid 1px #ccc; border-radius: 5px; margin: 20px; padding: 5px; } 
 <button id="btnRequest" type="button">Request data</button> <button id="btnCancelRequest" type="button">Cancel request</button> <div id="myDiv">The new content will print here.</div> 


很高兴知道这一点:

XMLHttpRequest.response属性返回响应的正文。 它可以是ArrayBufferBlobDocumentJavaScript对象或DOMString ,具体取决于XMLHttpRequest.responseType属性的值。 如果请求未完成或未成功,则响应值为null。 但是,如果responseType的值设置为"text"或空字符串,则当请求仍处于加载状态时,响应可以包含部分文本响应。

XMLHttpRequest.responseText属性返回一个DOMString包含请求为文本,或响应null ,如果请求不成功或尚未发送。 甚至在请求完成之前, responseText属性在到达时将具有部分响应。 如果responseType设置为空string"text"以外的任何其他值,则访问responseText将引发InvalidStateError异常。


您的代码必须是这样的:

$status = $_GET["status"];
if($status=="disp")
{
    $link = mysqli_connect("localhost", "root", "");
    mysqli_select_db($link,"checkbox");
    $res = mysqli_query($link,"SELECT * FROM table1");

    $html = "<table>"; // Declare a variable to concat the html content.
    while($row = mysqli_fetch_array($res))
    {
        $html += "<tr><td>";
        $html += $row["id"];
        $html += "</td><td>";
        $html += $row["name"];
        $html += "</td><td>";
        $html += $row["city"];
        $html += "</td></tr>";
    }
    $html += "</table>";
    echo $html; // Prints the $html variable.
}

在您的代码中,您需要删除:

<script src="jquery-3.2.1.min.js"></script>

如果您要使用本机则没有必要。

尝试这种方式

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "update.php?status=disp",false);
xmlhttp.send();

使用xmlhttp .send(); request页面发送request方法

为避免此warning ,请勿在perameter中使用false

async: false

XMLHttpRequest? 尝试使用“新的” Fetch API 请参阅: 浏览器对访存的支持

好的,IE不支持它。 以我的辩护,IE 11是唯一受支持的IE版本,如果他们拥有IE 11,则可能拥有Edge。

这是一个非常简单的示例:

fetch("example.com")
.then(
    function(response)
    {
        response.text()
        .then(
            function(result)
            {
                console.log(result);
            }
        );
    }
);

当然,您可以将"example.com"更改为您的网址。

以下是一个更详细的示例,展示了不同的选项,例如标头,请求方法,重定向,控制凭据(您要发送cookie和http auth?)并捕获异常。 我建议阅读有关使用获取的MDN文章以了解更多详细信息。

注意:您可以按预期在URL中传递GET参数。 对于POST请求,您必须将成员body添加到Request对象的初始化中。

var headers = new Headers();
headers.append('X-Requested-With', 'XMLHttpRequest'); // #lies
var request = new Request(
    "example.com",
    {
        method: "GET",
        headers: headers,
        mode: 'cors',
        credentials: 'same-origin',
        cache: 'default',
        redirect: 'follow'}
);
fetch(request)
.then(
    function(response)
    {
        // response status
        console.log('ok: ' + response.ok);
        console.log('status: ' + response.status); //e.g: 200
        // response headers
        console.log('X-Header: ' + response.headers.get('X-Header'));
        // response url (redirections)
        console.log(response.url);
        // body as text
        response.text()
        .then(
            function(result)
            {
                console.log(result);
            }
        );
    }
)
.catch(
    function(err)
    {
        console.log(err);
    }
);

注意:在示例中,我使用方法text来获取响应主体的文本。 您也可以使用json方法来获取主体并直接对其进行解析。 还有一个blob方法,如果响应除其他外为多媒体,则该方法很有用。

暂无
暂无

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

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