XMLhttpRequest >PHP >XMLhttp请求 [英] XMLhttpRequest > PHP > XMLhttpRequest
问题描述
我还有一个问题.XMLhttpRequests 困扰着我.现在一切都在数据库中,但我需要这些数据在第一次页面加载或重新加载时更新我的页面.XHR 在触发 PHP-Script 的 JavaScript 文件中触发.PHP-Script 访问 MySQL 数据库.但是如何将获取的记录返回到我的 JavaScript 中以进行页面更新.我想不通.
I have another question. XMLhttpRequests haunt me. Everything is now in the database but I need this data to update my page on firt page load or reload. The XHR is triggered in JavaScript file which triggers PHP-Script. PHP-Script access MySQL database. But how do I get the fetched records back into my JavaScript for page update. I can not figure it out.
首先是我的同步 XMLhttpRequest:
First my synchronous XMLhttpRequest:
function retrieveRowsDB()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","retrieveRowData.php", false);
xmlhttp.send(null);
return xmlhttp.responseText;
}
然后是我的 PHP 脚本:
Then my PHP-Script:
<?php
$con = mysql_connect("localhost","root","*************");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sadb", $con);
$data="SELECT * FROM users ORDER BY rowdata ASC";
if (!mysql_query($data,$con))
{
die('Error: ' . mysql_error());
}
else
{
$dbrecords = mysql_query($data,$con);
}
$rowdata = mysql_fetch_array($dbrecords);
return $rowdata;
mysql_close($con);
?>
我在这里错过了什么?有人知道吗?
What am I missing here? Anyone got a clue?
推荐答案
到目前为止,您的代码没有太多技术错误 - 您只需要实际做
There's not much technically wrong with your code so far - you just need to actually do something with it.
在您的 PHP 文件中,您需要以某种方式输出而不是 return $rowdata;
.目前,它只是将一个空白文档发送回 javascript,因此您需要 echo
输出代码.通常,当使用多个对象返回给 javascript 时,JSON 是一种很好的格式.查看json_encode
.
In your PHP file, instead of return $rowdata;
, you need to output it in some way. Currently, it's just sending a blank document back to the javascript, so you'll need to echo
out the code. Normally, when using a number of objects to be returned to javascript, JSON is a good format. Check out json_encode
.
另一方面,在 js 中,您需要获取响应并以某种方式更新页面.目前,您只是再次退货.
On the other side, in the js, you'll need to take the response and update the page in some manner. Currently, you're just returning it again.
我建议您阅读一些 ajax 教程,并考虑使用诸如 jQuery 之类的框架来完成繁重的工作为你.您可能还想阅读一些关于此主题的内容,因为您有一些基本的误解.
I suggest you go through a few ajax tutorials, and consider using a framework such as jQuery to do the heavy lifting for you. You might also want to do a bit of reading on this topic, as you have some fundamental misconceptions.
这篇关于XMLhttpRequest >PHP >XMLhttp请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!