简体   繁体   English

jQuery将数据发送到PHP并接收数据

[英]Jquery send data to PHP and receive data

I have a PHP script calling an API which takes a while to load, consequently users do not see the page for a while and believe something went wrong. 我有一个调用API的PHP脚本,该脚本需要一段时间才能加载,因此用户一段时间不会看到该页面,并认为出了点问题。

I have been informed that a Jquery script can send data to the PHP file, get the resulting data from it and display a loading message/animation while this is being performed. 我被告知,一个Jquery脚本可以将数据发送到PHP文件,从中获取结果数据并在执行过程中显示加载消息/动画。 Looking around the Internet I found this: 环顾互联网,我发现:

$.get("check.php", { url: "www.domain.com"}, function(data){
    alert("Data Loaded: " + data);
});

I've not been able to figure out how the PHP file needs to receive the sent data ( $_GET['url'] or otherwise) or how to receive and display the data and how to display a loading message. 我还无法弄清楚PHP文件如何需要接收发送的数据( $_GET['url']或其他方式),或者如何接收和显示数据以及如何显示加载消息。 A lot of questions I know, but I would be very grateful for any information to understand how to do this. 我知道很多问题,但是对于任何信息,我将不胜感激。

With the help of everyone who responded to this post this is the working result: 在回复此帖子的每个人的帮助下,这是工作结果:

<div id="content-area"><p>loading content...</p></div>

<script type="text/jscript">    
    $.get("check.php", { url: "www.domain.com"}, function(data){
    $("#content-area").html(data)
    });
</script>

The PHP receives the data with a GET method and returns data with echo. PHP使用GET方法接收数据,并使用echo返回数据。

Thanks everyone for your help :) 谢谢大家的帮助:)

The way to do this is to display a loading message/animation by default and then, once it does get loaded, your jQuery $.get() method would fill in the content. 做到这一点的方法是默认显示一条加载消息/动画,然后,一旦加载它,您的jQuery $.get()方法将填写内容。

For check.php to receive the data from jQuery, it gets treated like any other GET request to the script. 为了使check.php从jQuery接收数据,它像对待脚本的任何其他GET请求一样被对待。 In this case, it would be like going to check.php?url=www.domain.com and whatever output is generated would get received in the ' data ' parameter. 在这种情况下,就像去check.php?url=www.domain.com ,生成的任何输出都将被接收到' data '参数中。

// On some sort event, here click is used for example
$('button').click(function() {
   // start loading message
   console.log('loading...');
   // start request
   $.get("check.php", { url: "www.domain.com"}, function(data){
       // this part is triggered when request is successful
       console.log('LOADED');
       // shows what was echo'ed on php file
       console.log(data);
   });
});

console.log() show messages in Developer Tools console console.log()在开发人员工具控制台中显示消息

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

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