我经历了许多解决方案1,但在java脚本中没有得到json,因此出现了错误。在我的myfile.php文件中,它包含
<?php
................
print json_encode($data, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="example2.js"></script>
<script>
var json= loadJsonFromPHP(<?php echo json_encode($data) ?>);
//var json= <?php echo json_encode($data) ?>;
</script>
</head>
<body></body>
</html>
在我的示例2.js文件中
var loadJsonFromPHP = function(json) {
console.log(json);
}
function init(){
// init data
var json =loadJsonFromPHP(json);
}
获取错误无法在console.log(json)中读取未定义的属性"id",我是PHP新手,不知道我哪里错了,
我在js中尝试过.getJson,但得到的错误ReferenceError:$没有定义
function init(){
// init data
var json=$.getJSON('http://localhost/myfile.php', function(data) {
console.log(data);
});
}
完全卡住了,有任何帮助,谢谢。
myfile.php应该只包含echo json_encode($data)
在"myfile.php"中,您可以执行以下操作。。。
<?php
$array = array(
"success" => true,
"message" => "Greetings from the Server!"
);
echo json_encode($array);
?>
在您的HTML文件中。。。
<html>
<head>
<script src='js/jquery.js'></script> <!-- your path to jquery goes here -->
</head>
<body>
<div id="target">Message from Server will appear here</div>
<script type="text/javascript">
// On ready
$(function() {
$.ajax({
url: 'myfile.php',
// Before sending the request, show a loading message
beforeSend: function(){
$("#target").html("Waiting for response...");
}
})
.done(function(response){
// Write the response message to the target div
$("#target").html(response.message);
});
</script>
<body>
</html>
这真的应该做到。
您可以在此处参考.ajax
的jQuery文档:http://api.jquery.com/jQuery.ajax/
在javascript中,您需要解析JSON字符串:
var jsonobj = JSON.parse('<?php echo json_encode($data) ?>');
在http://localhost/myfile.php
中,确保您有:
//You cannot have any echo here you must have clean json-string.
$json = json_encode( $data );
if( json_last_error() === JSON_ERROR_NONE ){
http_response_code(200);//ok
header('Content-type: application/json');
die( $json );
}else{
http_response_code(500);//server error
die( 'Cannot encode $data.' );
}
最后XMLHttpRequest在example2.js中为我解决了问题,希望它能有所帮助。
request = new XMLHttpRequest( );
request.open("GET", "my.php", false);
request.send(null);
var json = eval ("(" + request.response + ")");