如何从javascript返回输出json

时间:2015-03-23 10:08:45

标签: javascript php json

我有一个带有此代码的页面php:



<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing,geometry"></script>

<script type="text/javascript">	

console.log(" cap in <?php print $_POST['CAP'] ?>");

var v_lat_to = '<?php print $_POST['LAT_TO'].$_GET['LAT_TO'] ?>';
var v_lng_to = '<?php print $_POST['LNG_TO'].$_GET['LNG_TO'] ?>';
var v_lat_from = '<?php print $_POST['LAT_FROM'].$_GET['LAT_FROM'] ?>';
var v_lng_from = '<?php print $_POST['LNG_FROM'].$_GET['LNG_FROM'] ?>';
var v_cap_from = '<?php print $_POST['CAP'].$_GET['CAP'] ?>';
var v_npax = '<?php print $_POST['N_PAX'].$_GET['N_PAX'] ?>';
var v_ora =  '<?php print $_POST['ORA'].$_GET['ORA'] ?>';
var v_min =  '<?php print $_POST['MIN'].$_GET['MIN'] ?>';

var v_price = 0;
var v_result = "OK";

if(v_lat_to == '' && v_lng_to == ''){
	v_result = "KO - Coordinate di destinazione non valorizzate";	
	console.log("KO - Coordinate di destinazione non valorizzate");
}
else if(v_cap_from == "" && v_lat_from == "" && v_lng_from == ""){
	v_result = "KO - Coordinate di partenza non valorizzate";	
	console.log("KO - Coordinate di partenza non valorizzate");
}

/*
* ...
* ...
* others code with logic javascript
*
*/

// return the output with object json
var jsonObj = [];
var item = {};
item["price"]=v_price;
item["result"]=v_result;

jsonObj.push(item);

document.write(JSON.stringify(jsonObj));

</script>
&#13;
&#13;
&#13;

当我调用这个php页面时,我没有在输出中找到对象json,但是有完整的代码javascript。

从javascript创建json是否正确?

2 个答案:

答案 0 :(得分:0)

您的解决方案是ajax

<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/Customers_MYSQL.php";

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
    var arr = JSON.parse(response);
    var i;
    var out = "<table>";

    for(i = 0; i < arr.length; i++) {
        out += "<tr><td>" +
        arr[i].Name +
        "</td><td>" +
        arr[i].City +
        "</td><td>" +
        arr[i].Country +
        "</td></tr>";
    }
    out += "</table>"
    document.getElementById("id01").innerHTML = out;
}
</script>

more Information

答案 1 :(得分:0)

[{"price":0,"result":"KO - Coordinate di destinazione non valorizzate"}]
这是你想要的吗?您正在查看完整的JavaScript,因为您没有通过网络服务器调用该php文件。我认为您正试图像本地文件一样直接访问它。