我有code.php,这个文件计算数量和价格我希望通过ajax将结果thtat返回到index.php
code.php
$query = 'select * from products where sku='."'$sku'";
$result=mysql_query($query);
$qty = $_GET['qty'];
$price_egp=number_format((float)($product['price1']*12.5), 3, '.', '');
$arr = array ('price'=>"$price",'qty'=>"$qty");
echo json_encode($arr);
结果是
{"price":"40.9504305591","qty":"50"}
我想在index.php中的code.php中返回值
的index.php
function updateItems(ID,price){
var qty= document.getElementById( ID).value;
//$('#'+target).html(price*qty);
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//here i want to return response(#qty).html();/*i don't know how rturn data from json here inside html */(#price).html();
}
}
xmlhttp.open("GET","code.php?op=updateItems&qty="+qty+"&price="+price+"&id="+itemIndex+"&sku="+ID,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send()
}
enter code here
html代码
答案 0 :(得分:0)
在回调函数中使用JSON.parse
xmlhttp.onreadystatechange = function() {
var result = JSON.parse(xmlhttp.responseText);
var price = parseFloat(result.price);
var qty = parseInt(result.qty, 10);
// Do what you want with price and qty
};
答案 1 :(得分:0)
你可以这样做:
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var json = JSON.parse(xmlhttp.responseText);
document.getElementById('qty').innerHTML = parseInt(json.qty);
document.getElementById('price').innerHTML = parseFloat(json.price);
}