Json request with Javascript
I am just beginner on java script and JSON and never had done any work in these before. My employer has just asked me to create the basic POC of these.
Scenario: I have a REST API and when i call it, it returns back re开发者_C百科sponse in JSON format. Need to To: Create a HTML page and use javascript to call that REST API and capture JSON response and print in the same HTML page.<script type="text/javascript">
function loadMe() {
loadJSON('http://myrestAPI');
}
function loadJSON(url) {
//Help me here to capture the response and print in html page.
}
</script>
I would appreciate your help. This might be simple, but for me i have no idea because i never have done anything similar in java script and json. I goggled but could not find anything.
Thanks, chota
function SendRequest(MSG)
{
var objJSON = {
"msg" : MSG
};
var strJSON = encodeURIComponent(JSON.stringify(objJSON));
new Ajax.Request("ReceiveJSON.jsp",
{
method: "post",
parameters: "strJSON=" + strJSON,
onComplete: Respond
});
}
function Respond(REQ)
{
document.getElementById("ResponseDiv").innerHTML=REQ.responseText;
}
If you view your REST request response, the JSON might be something like this
{
"users": [
{"first": "Peter",
"last": "Griffin"}
],
"books": [
{"title": "Design Patterns",
"author": "The Gang of Four",
"year": 1995}
]
}
This rest query result can be loaded as a javascript array object
<script language="javascript">
var resultObj = <Result of your REST url + query pasted here>;
</script>
Then,
you access it in your html with javascript blocks like
document.write(resultObj.users[0].first)
which would return 'Peter'
Praneeth has the simple javascript answer. If you can use jquery (and there really is no reason you cannot) it gets way easier:
<div id="response"></div>
$.get(url, function(data) {
$('#response').append(data.property);
});
$.getJSON(url, null, function (data) { .... });
Here's a complete working example using jQuery that should work.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.0.min.js"></script>
</head>
<body>
<div id="response">
<p id="responseParagraph">Base text</p>
</div>
<script>
$.getJSON('http://myrestAPI',
function(data) {
$('#responseParagraph').append("<p>"+data.responseMessage+"</p>");
});
</script>
</body>
</html>
精彩评论