我遇到一个问题,我的Js文件无法识别ajax构建的php变量。这里有一个例子:
index.php:
<script src="js.js">
</script>
<?
include('build.php');
<div id="brand">
<?
echo $brandinput;
?>
</div>
//....more code
?>
build.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function(data){
$("#result").html(data);
}
});
</script>
<?php $brandinput='<div id="result"></div>';
?>
js.js:
$(document).ready(function(){
//dosomething with div's in index.php
}
所以,我将尝试用最简单的方式来解释这一点。我的index.php包含一个build.php,您可以看到它调用ajax从另一台服务器检索数据。该数据位于一个php变量($brandinput
)中,该变量将包含许多<div>,<input>,... etc.
然后index.php echo$brandinput,显示该变量的所有内容。但我有一个js.js,它会改变div、input等的外观。这个js无法识别变量$brandinput的内容。
我想知道你是否有更多的想法,或者我做错了什么。。。所有的代码都运行良好,我测试了很多次(除了我之前说过的)ajax调用运行良好,Index.php正确显示$braninput
。
p.s.$brandinput
是这样的:
<div id='BlackBerry'><img src='..'/images'/supporteddevices'/blackberry-logo.jpg' alt='blackberry-logo' width='75'><br><input class='adjustRadio' type='radio'
是的,它也很有效。
实际上这就是它应该如何工作的,您需要做的是在执行js.js
中的函数之前先等待ajax请求完成
试试这种方式
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
//dosomething with div's in index.php
}
});
});
或者(假设js.js是在build.php中的脚本之后加载的,或者js.js必须在它之后加载)
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
}
});
});
// in js.js
$(document).ready(function () {
promise.then(function (data) {
//dosomething with div's in index.php
});
});
p.S
$brandinput
只保存指定给它的字符串,并且永远不会随着ajax请求而更改,其中ajax成功处理程序只在客户端直接操作渲染的DOM。
您可以尝试将<script>
标记移动到php代码后面,如下所示:
<? include('build.php'); ?>
<div id="brand">
<? echo $brandinput; ?>
</div>
<script src="js.js"></script>
//....more code
稍微不同的是,您应该考虑避免将PHP代码与HTML和Javascript嵌入/混合。看看这篇文章,了解"将数据从PHP传递到Javascript"的更好方法。