如何使用Ajax将变量值从PHP发送到Javascript?下面是JS代码和PHP代码
PHP代码:
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = @mysql_connect($hostname, $username, $password);
if(@mysql_select_db("trainer_registration"))
{
echo "Connected Successfully";
}
else
{
echo "Connection Error";
}
$select_query_num = @mysql_query("select id,program_name,company,date_prog from program_details");
$num_rows = @mysql_num_rows($select_query_num);
for ($i = 0; $i <= $num_rows; $i++){
$id = $_POST["idjs"];
$pgmname = $_POST["pgmnamejs"];
$comp = $_POST["compjs"];
$datephp = $_POST["datephpjs"];
$select_query = @mysql_query("select id,program_name,company,date_prog from program_details where id = $i");
$fetch_query = @mysql_fetch_assoc($select_query);
$id = $fetch_query['id'];
echo $id;
$pgmname = $fetch_query['program_name'];
echo $pgmname;
$comp = $fetch_query['company'];
echo $comp;
$datephp = $fetch_query['date_prog'];
echo $datephp;
}
?>
JS CODE:
window.onload = function createdivs() {
var id;
var pgmname;
var comp;
var datephp;
var i = 1;
for (;i < 10;i++)
{
div = "<div>.display";
var list = document.createElement("div");
document.getElementById('fulldisplay').appendChild(list);
list.className = "container content-rows";
}
$.ajax({
url:'displaycontent.php',
data:{idjs:id, pgmnamejs:pgmname, compjs:comp, datephpjs:datephp},
type:'POST',
success:function(retval){
alert(retval);
}
});
}
问题:
在JS CODE中,对于var i的每个增量,我需要对PHP文件进行Ajax调用,该文件应该返回第一个数组值,然后返回第二个数据库,依此类推。我真的很困惑如何做到这一点。解释会更好。通过上面的代码,我只获得了一个带有未识别索引错误的最后一个数组值。
答案 0 :(得分:0)
如果这不是正式的工作,那么只需在php脚本中回显HTML。
org.hibernate.AnnotationException: A Foreign key refering com.mysite.model.SellerProduct from com.mysite.model.Product has the wrong number of column. should be 2
答案 1 :(得分:0)
我不是PHP专家,但似乎你应该有类似的东西:
echo '<script type="text/javascript">';
// bunch of:
echo ' var myvar = ' + $fetch_query['myvar'] + ';';
// probably use a proper way to escape those things
echo '</script>';
或构建php变量的小型全局可访问版本的任何内容......
最好的方式是:
我见过关于angularjs的评论,花一些时间使用正确的javascript框架绝对不会浪费你的时间IMO!
答案 2 :(得分:0)
你需要对来自$ select_query的结果使用json编码然后你可以使用ajax将结果转换为javascript
//echo the json_encode in php to see the results
json_encode($select_query)
//do ajax with jquery
$.ajax({
url: 'the page that has the $select_query which brings the results',
type: 'POST',
dataType: 'json',
data: data,
succes: function(data){
console.log(data);
}
});
现在您可以根据需要操作数据。