嗯..。我正尝试在jquery中使用php变量,在我的edit.php中:我想使用jquery来显示php变量,使用"rel“属性,但它给了我变量的”名称“,而不是它的内容。
我使用php从xml文件中检索文本:(编辑:单击提交不会更新文本,但单击两次可以更新文本)
/* READ */
$dom = new DomDocument();
$dom->load('edition.xml');
$_home = $dom->getElementsByTagName('home')->item(0);
$home = $_home->firstChild->nodeValue;
$_rhizo = $dom->getElementsByTagName('rhizo')->item(0);
$rhizo = $_rhizo->firstChild->nodeValue;
$_disco = $dom->getElementsByTagName('disco')->item(0);
$disco = $_disco->firstChild->nodeValue;
/* array */
$rels = array('home' => $home,
'rhizo' =>$rhizo,
'disco' =>$disco);
echo '<script>var rels = ' . json_encode($rels) . '</script>';
/* WRITE */
if ( isset($_POST['cache']) ){
if ( isset($_POST['home']) ){
$home = stripslashes($_POST['home']);
$_home->firstChild->nodeValue = $home;
}
if ( isset($_POST['rhizo']) ){
$rhizo = stripslashes($_POST['rhizo']);
$_rhizo->firstChild->nodeValue = $rhizo;
}
if ( isset($_POST['disco']) ){
$disco = stripslashes($_POST['disco']);
$_disco->firstChild->nodeValue = $disco;
}
$dom->save('edition.xml');
}
?>(文本简单地显示在一个textarea中,我只是将php变量放在这里),然后我使用jquery显示来自php变量的内容:(使用数组对象进行编辑:)
$('#left a').bind('click', function(){
var text_from_link = $(this).text();
var rel = $(this).attr('rel');
$('#textarea1').attr('name', rel);
$('#textarea1').text(rels[''+rel+'']);//output is "$home" for example, which will retrieve the "home" part from the xml
return false;
})如果我双击submit,如果我只点击一次,文本不会更新...我对此有点困惑
谢谢你的帮忙
发布于 2011-11-01 06:32:37
您需要执行ajax调用才能做到这一点。
或者,您可以在HTML中编写javascript对象:
$rels = array('rel23' => 'Hello world');
echo '<script>var rels = ' . json_encode($rels) . '</script>';然后使用javascript访问它们:
alert(rels.rel23);发布于 2011-11-01 06:37:32
如前所述,您需要使用ajax来完成此任务。jQuery提供了ajax,看起来你已经在使用它了。
if(isset($_POST["getHome"])) {
$dom = new DomDocument();
$dom->load('edition.xml');
$_home = $dom->getElementsByTagName('home')->item(0);
$home = $_home->firstChild->nodeValue;
echo $home; // anything returned by this page will become 'data'
}和
$(function(){
$('a').bind('click', function(){
$.post("mypage.php",{getHome : 1}, function(data) {
alert(data);
});
})
});好的,假设您的php中有一个数组
if(isset($_POST["varName"])) { // will check if the POST variable with the name 'varName' is set
$arr = array(1,2,3); // your array
echo json_encode($arr); // encode your output as a json string
}然后在你的javascript中
$(function(){
$('a').bind('click', function(){
$.post("mypage.php",{varName: 1}, function(data) { // the value of 1 is trivial. and is likely not needed, you can post to a page without passing any values. In which case the use if isset() in php is not required.
var json_obj = JSON.parse(data);
console.log(json_obj); // assuming you have a console at your disposal.
});
})
});https://stackoverflow.com/questions/7960554
复制相似问题