通过AJAX调用将PHP变量转换为jquery脚本文件
So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results. My php file is echoing data that should be printed in my results div. Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
所以基本上我有两个文件。 1是我的php文件,它在调用时创建带有一些变量的表,第二个文件是调用该调用的jquery脚本文件。 我的脚本文件: p>
$。ajax({
type:'POST',
data:({p:2,ank:ankieta,wybrane:wybrane}) ,
url:'zestawienia_db.php',
success:function(data){
$('#results')。html(data);
}
});
code > pre>
打印结果可以正常工作。
我的php文件正在回显应该在我的结果div中打印的数据。
问题是如何获取一些PHP数据变量并能够在我的jquery文件中使用它们而不实际回应它们? strong> p>
div>
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1
on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so echo data[0]; which in this case wiill echo the text peiceofdata.
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({ type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});