在ajax中有没有一种方法可以使其运行php脚本?

时间:2019-07-10 21:04:19

标签: jquery ajax

我需要一种在游戏中排行榜的方法,而且我已经准备好使用PHP脚本来接收所有内容。是否可以使用ajax来运行该脚本(有或没有JQuery)?如果可以,怎么办?

2 个答案:

答案 0 :(得分:0)

如果要在游戏中排行榜,则不应使用常量XMLHttpRequest或fetch(),而应使用node.js服务器或某些其他WebSocket托管所有这些数据并将这些数据实时发送给他们。如果您不希望它是实时的,而是让它将排行榜显示为静态网页,则可以在JavaScript中使用XMLHttpRequest方法,例如

var xhttp;
var response;
try {
  xhttp = new XMLHttpRequest();
}
catch(e) {
  xhttp = new ActiveXObject();
}
xhttp.onreadystatechange = function() {
  if (this.readyState == 4) { //Finished Request
    if (this.status == 200) { //Found file successfully
      response = xhttp.responseText; //Or use xhttp.responseXML to get the response as XML
    }
  }
}
xhttp.open("GET","yourphpfile.php",true);
xhttp.send();

这将使您的变量,响应具有您在PHP文件或XML(如果您使用responseXML)中回显的所有值。

答案 1 :(得分:0)

您的问题非常广泛,下面是一些伪造的代码,它们的命名将为您指明正确的方向。

Ajax查询

$.ajaz({
    type:"post",
    url:"yoururl.com/phpfile.php",
    data:yourSerializedData,
    success:function(ajaxResponse)
    {
        FunctionForResponse(ajaxResponse);
    },
    error: function(error)
    {
        console.log.(error);
    }
});

PHP文件(“ yoururl.com/phpfile.php”)

if(isset($_POST['nameOfSomethingFromYourSerializedData']))
{
    //Do Something with the data posted to this via Ajax

    //return response with echo

    $ajaxResponse = "You just posted data to a PHP file with Ajax";
    echo $ajaxResponse;
}

使用此(未测试的notepad ++快速类型)伪代码,您应该不会遇到编写自己的问题,如果一旦编写自己的内容,便会遇到一个问题,并提出有关该特定问题的问题。