<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function get_msg(){
//ajax请求接受,js做处理
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
// alert(typeof xhr.responseText);//
eval("var people="+xhr.responseText);
console.log(people);
document.getElementById('res').innerHTML = eval;
}
}
xhr.open('get','./3.php');
xhr.send(null);
}
//把string变为object对象
//eval() 字符串参数->表达式 来运行
</script>
</head>
<body>
<h2>接受信息 并 读取</h2>
<input type="button" value="获取" onclick="get_msg()">
<p id="res"></p>
</body>
</html>
I want to add a p to the page and output the content here, but it seems wrong for me to write it this way. How can I add an ID to console.log? Or how to output the contents of console.log to p?
The proposition itself is somewhat problematic. The function of console.log() is for code debugging, which is console output. The purpose of this method is to display the content you do not want to display on the page in the console to facilitate code debugging. If you want to output on the page, there are many methods. Element.innnerHTML and Element.text() are good choices. Even worse, there is the violent document.write() method. Why bother to find the console? content and then output it to the page? In other words, as long as you can console the content, you can use document.write() to the page
The code of the question is just an ajax, what does eval mean? What does xhr.send(null) mean? What's more, even if xhr.readyState==4: true, this only means that the background has received data, but do you have to judge whether the data is returned to you?
If you are doing native ajax, it is best to pay attention to the control of status codes and handle the business logic well. If you use jquery or angular, it will be a better choice
Console.log prints the content of people, so the content of your innerHTML is people. What does it mean when you write eval
Just var people and then assign the value, and then add people to the corresponding position. Don't use eval blindly.
Use the eval function with caution. Directly put the content you need to print into a variable. Then innerhtml or innertext
Output to page innerText or innerHTML is fine