我不确定这是否已得到解决(我确信它可能已经解决了),但我遇到了问题并且无法找到我正在寻找的确切内容。以下是我的聊天室内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
body {
font:16px Helvetica;
color: #a8199f;
text-align:center;
padding:35px; }
form, p, span {
margin:0;
padding:0; }
input {
font:16px Helvetica; }
a {
color:#0000FF;
text-decoration:none; }
a:hover {
text-decoration:underline; }
#wrapper {
margin:0 auto;
padding-bottom:25px;
background: #bdbbb7;
width:50%;
border:1px solid #ACD8F0; }
#chatbox {
text-align:left;
margin:0 auto;
margin-bottom:25px;
padding:10px;
background:#fff;
width:50%;
border:1px solid #ACD8F0;
overflow:auto; }
#chatbox p {
padding:1em;
margin:1em;
background:#afd6ed;
border:1px solid #BDBDBD;
-moz-border-radius:4px;
}
#usermsg {
width:50%;
border:1px solid #ACD8F0; }
#submit {
width: 60px; }
.welcome {
float:left; }
.logout {
float:right; }
.msgln {
margin:0 0 2px 0; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script>
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome</p>
<p class="logout"><a id="exit" href="#" onclick="window.close();">Exit Chat</a></p>
<div style="clear:both"></div>
</div>
<div id="chatbox">
<p>Here's our chat data</p>
<div id="update"></div>
</div>
<form name="message">
<input name="usermsg" type="text" id="usermsg" size="63" />
<button type="button" id="submitmsg" value="send">Send</button>
</form>
</div>
<script>
$(document).ready(function(){
$('#submitmsg').click(function(){
var message = $('#usermsg').val();
$('#chatbox').append('<p>' + message + '</p>');
$('#usermsg').val('');
});
});
function close_window(url){
var newWindow = window.open('', '_self', ''); //open the current window
window.close(url);
};
</script>
<script src="script.js"></script>
</body>
</html>
我想制作这个.json文件:
[
{
"response":"Hello",
},
{
"response":"How may I help you?",
},
{
"response":"Let me look into that for you.",
},
{
"response":"Can you give me more information about that?",
},
{
"response":"Is there anything else I can help you with?",
},
{
"response":"Thank you, Have a good day.",
}
]
是用户消息的响应。我已经尝试过这个脚本,但我知道我错过了一些东西,似乎无法自己掌握它或找到适当的信息。任何帮助或参考将不胜感激。谢谢。
$('#usermsg').keyup(function(){
var userResponse = $('#usermsg').val();
$.getJSON('data.json', function(data){
var output = '<div class="repsonse">';
$.each(data, function(key, val){
if(val.response != -1){
output += '<p>' + val.response + '</p>';
});
output += '</div>';
$('#update').html(output);
});
});
答案 0 :(得分:0)
AJAX请求getJSON
是异步且无阻塞的。 function(data)
方法是回调,仅在.getJSON()
请求成功完成时运行。而示例中的$('#update').html(output)
会立即运行 - 它不会等待ajax请求完成。
您需要将DOM操作移动到回调中:
$.getJSON('data.json', function(data) {
var output = '<div class="repsonse">';
$.each(data, function(key, val) {
if (val.response != -1) {
output += '<p>' + val.response + '</p>';
}
});//end each
output += '</div>';
$('#update').html(output);
});