如何使用ajax获取数据并将render元素作为List Group中的Bootstrap List Group Item

时间:2017-03-25 02:50:21

标签: jquery json ajax bootstrapping

我正在尝试使用AJAX从外部链接获取json数据,而不是打印输出。我尝试了以下方式,但这对我没用。而且我不确定如何将元素渲染为列表组中的Bootstrap List Group Item

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script         src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script     src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript"
src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</script>
</head>
<body>
<button id="fetchBtn">Fetch</button>
<ul id="results"></ul>
<script>
$(document).ready(fuction(){
$('fetchBtn').click(function(){
$.ajax({
 type: 'get',
 url: 'http://jsonplaceholder.typicode.com/users',
 data: {},
 dataType: 'json',
 success: function (users){
 user.forEach(function(user){
$('#result').append('<li>' + user.name+ '</li>');
});
 };

error: function(xhr, status,errorThrown){
};
complete: function(xhr, status){
}
});
});
render() {
return (
<div>
<h1>{`users`}</h1>
<ul>
    {users.state.posts.map(post =>
        <li key={post.id}>{post.title}</li>
          )}
    </ul>
  </div>

);
}
});

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

你有很多错别字。我试图修复所有这些问题。剩下的问题是render()功能,我不太了解应该做什么。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script         src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script     src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript"
src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</script>
</head>
<body>
<button id="fetchBtn">Fetch</button>
<ul id="results"></ul>
<script>
$(document).ready(function(){
$('fetchBtn').click(function(){
$.ajax({
 type: 'get',
 url: 'http://jsonplaceholder.typicode.com/users',
 data: {},
 dataType: 'json',
 success: function (users){
 users.forEach(function(user){
$('#result').append('<li>' + user.name+ '</li>');
});
 },

error: function(xhr, status,errorThrown){
},
complete: function(xhr, status){
},
});
});
render() {
return (
<div>
<h1>{`users`}</h1>
<ul>
    {users.state.posts.map(post =>
        <li key={post.id}>{post.title}</li>
          )}
    </ul>
  </div>

);
}
});

</script>
</body>
</html>