ok I have edited this to another couple of questions I've asked on a similar issue, but I really am in a rush so thought I'd start a new one, sorry if it bothers anyone.
好吧,我把它编辑成另外几个问题,我问过类似的问题,但是我真的很忙,所以我想我应该重新开始,如果有人介意的话,不好意思。
first I have a php script on test.php on the apache server
首先,我有一个测试中的php脚本。apache服务器上的php
<?php
//create connection
$con = mysqli_connect("localhost", "user", "password", "dbname");
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Then I've got this ajax script set to fire onload of page a webpage written in html. so the load() function is onload of the page in the body tag. This script is in the head.
然后,我将这个ajax脚本设置为以html格式编写的页面加载页面。所以load()函数是body标记中的页面的onload。这个脚本在头脑中。
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
ok so what I want is the $n1 variable in the php script to be used in the javascript ajax code. Where the script is, but I'm not sure where or how to make use of the variable, I've tried a few things. All that happens right now is the innerHTML of itemNameLink1 just disappears.
好的,我想要的是php脚本中的$n1变量,用于javascript ajax代码。脚本在哪里,但是我不确定在哪里或者如何使用这个变量,我尝试了一些东西。现在发生的就是itemNameLink1的innerHTML消失了。
I'm quite new so any advise would be appreciated, thanks.
我是新来的,希望你能给我一些建议,谢谢。
3 个解决方案
#1
1
The response (this is what you echo in php) returned from request you can get by responseText
attribute of XMLHttpRequest
object. So first your JS code should be:
从XMLHttpRequest对象的responseText属性获取的请求返回的响应(这是php中的回调)。首先你的JS代码应该是:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
}
}
}
now in php echo $n1
variable:
现在php中echo $n1变量:
....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
// echo it to be returned to the request
echo $n1;
Update to use JSON for multiple variables
对多个变量使用JSON进行更新
so if we do this:
如果我们这样做:
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$response = array
(
'name' => $name,
'color' => $color,
'price' => $price
);
echo json_encode($response);
Then in javascript we can parse it again to have data object containing 3 variables.
然后,在javascript中,我们可以再次解析它,以拥有包含3个变量的数据对象。
var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text
Fetching all the rows:
获取所有的行:
$row = mysqli_fetch_array($grab); // this will fetch the data only once
you need to cycle through the result-set got from database: also better for performance to use assoc instead of array
您需要循环从数据库获得的结果集:也可以更好地使用assoc而不是数组。
$names = $color = $price = array();
while($row = mysqli_fetch_assoc($grab))
{
$names[] = $row['name'];
$color[] = $row['color'];
$price[] = $row['price'];
}
$response = array
(
'names' => $names,
'color' => $color,
'price' => $price
);
#2
1
You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:
您可以使用php动态生成一个javascript文档,其中包含声明为javascript变量的服务器端变量,然后将其链接到文档的头部,然后在需要服务器端变量时将其包含到文档头中。这还允许在生成页面时动态更新变量值,例如,如果在每个页面加载上有一个nonce或需要更改的内容,那么可以在每个页面加载时传递正确的值。要做到这一点,你需要做一些事情。首先,创建一个php脚本并声明正确的标题,以便将其解释为脚本:
jsVars.php:
jsVars.php:
<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
//create the javascript object
?>
var account = {
email: <?= $n1; ?>,
//if you need other account information, you can also add those into the object here
username: <?= /*some username variable here for example */ ?>
}
You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:
对于需要在页面加载时传递给javascript的任何其他信息,您都可以重复这一点,然后使用名称空间javascript对象引用您的数据(使用对象名称空间将避免与其他可能没有预料到的脚本变量发生冲突)。
<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>
You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.
您还可以将一个条件语句放入文档的头部,这样它只会在需要它的页面上加载(或者任何权限检查或其他标准通过)。如果您在其他脚本文件之前加载它,那么它将在所有脚本文件中都可用,前提是您在比请求更高的范围内使用它。
<head>
<?php
//set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
if($require_user_info == TRUE): ?>
<script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />
<?php endif; ?>
<script type="text/javascript" href="your-other-script-files-that-normally-load" />
</head>
You can also do this for any other scripts that have to load under specific criteria from the server.
您还可以对任何其他脚本执行此操作,这些脚本必须在服务器的特定条件下加载。
#3
1
You should define the PHP variable. And use that variable in your javascript:
您应该定义PHP变量。在javascript中使用这个变量:
<?php
$n1 = "asd";
?>
<html>
<head></head>
<body>
<div id="itemNameLink1"></div>
<script>
function load()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/test.php', true);
xmlhttp.send(null);
//Note you used `onreadystatecahnge` instead of `onreadystatechange`
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
}
}
}
load();
</script>
</body>
</html>
#1
1
The response (this is what you echo in php) returned from request you can get by responseText
attribute of XMLHttpRequest
object. So first your JS code should be:
从XMLHttpRequest对象的responseText属性获取的请求返回的响应(这是php中的回调)。首先你的JS代码应该是:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
}
}
}
now in php echo $n1
variable:
现在php中echo $n1变量:
....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
// echo it to be returned to the request
echo $n1;
Update to use JSON for multiple variables
对多个变量使用JSON进行更新
so if we do this:
如果我们这样做:
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$response = array
(
'name' => $name,
'color' => $color,
'price' => $price
);
echo json_encode($response);
Then in javascript we can parse it again to have data object containing 3 variables.
然后,在javascript中,我们可以再次解析它,以拥有包含3个变量的数据对象。
var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text
Fetching all the rows:
获取所有的行:
$row = mysqli_fetch_array($grab); // this will fetch the data only once
you need to cycle through the result-set got from database: also better for performance to use assoc instead of array
您需要循环从数据库获得的结果集:也可以更好地使用assoc而不是数组。
$names = $color = $price = array();
while($row = mysqli_fetch_assoc($grab))
{
$names[] = $row['name'];
$color[] = $row['color'];
$price[] = $row['price'];
}
$response = array
(
'names' => $names,
'color' => $color,
'price' => $price
);
#2
1
You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:
您可以使用php动态生成一个javascript文档,其中包含声明为javascript变量的服务器端变量,然后将其链接到文档的头部,然后在需要服务器端变量时将其包含到文档头中。这还允许在生成页面时动态更新变量值,例如,如果在每个页面加载上有一个nonce或需要更改的内容,那么可以在每个页面加载时传递正确的值。要做到这一点,你需要做一些事情。首先,创建一个php脚本并声明正确的标题,以便将其解释为脚本:
jsVars.php:
jsVars.php:
<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
//create the javascript object
?>
var account = {
email: <?= $n1; ?>,
//if you need other account information, you can also add those into the object here
username: <?= /*some username variable here for example */ ?>
}
You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:
对于需要在页面加载时传递给javascript的任何其他信息,您都可以重复这一点,然后使用名称空间javascript对象引用您的数据(使用对象名称空间将避免与其他可能没有预料到的脚本变量发生冲突)。
<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>
You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.
您还可以将一个条件语句放入文档的头部,这样它只会在需要它的页面上加载(或者任何权限检查或其他标准通过)。如果您在其他脚本文件之前加载它,那么它将在所有脚本文件中都可用,前提是您在比请求更高的范围内使用它。
<head>
<?php
//set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
if($require_user_info == TRUE): ?>
<script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />
<?php endif; ?>
<script type="text/javascript" href="your-other-script-files-that-normally-load" />
</head>
You can also do this for any other scripts that have to load under specific criteria from the server.
您还可以对任何其他脚本执行此操作,这些脚本必须在服务器的特定条件下加载。
#3
1
You should define the PHP variable. And use that variable in your javascript:
您应该定义PHP变量。在javascript中使用这个变量:
<?php
$n1 = "asd";
?>
<html>
<head></head>
<body>
<div id="itemNameLink1"></div>
<script>
function load()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/test.php', true);
xmlhttp.send(null);
//Note you used `onreadystatecahnge` instead of `onreadystatechange`
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
}
}
}
load();
</script>
</body>
</html>