我有一个问题,我的 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、输入等的外观。并且这个 js 无法识别变量 $brandinput 的内容。
我想知道您是否有更多想法或者我做错了什么......
所有代码都运行良好,我测试了很多次(除了我之前所说的)
ajax 调用运行良好,Index.php 显示 $braninput
正确。
附: $brandinput
是这样的:
<div id='BlackBerry'><img src='..\/images\/supporteddevices\/blackberry-logo.jpg' alt='blackberry-logo' width='75'><br><input class='adjustRadio' type='radio'
是的,它也运作良好。
最佳答案
其实应该是这样的,你需要做的是先等待ajax请求完成,然后再执行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);
//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
});
});
附注
$brandinput
只是保存分配给的字符串,并且永远不会随着 ajax 请求而更改,其中 ajax 成功处理程序只是直接在客户端操作渲染的 DOM。
关于javascript(ajax) 和 php 一起工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828448/