Explanation
Hm.. let's see if I can properly demonstrate this.
$.get()
is a shorthand for $.ajax()
.
So when you do this
$.get(uri, function(data){
console.log(data); // --> the entire page's content is logged
});
You're really doing this
$.ajax({
url: uri,
type: "GET",
success: function(msg){
console.log(msg);
}
});
And by default, it returns the page as HTML. Or rather, by default, it first checks the MIME-type on the page, and if none is found, it returns HTML. If you want to tell it what you would like to return, you can either do it in the MIME-type on the server page, or you could use $.getJSON()
If you want the data returned from your request in form of an object, JSON is the way to go.
The only real difference in the code, really, is
replace your $.get()
with $.getJSON()
$.getJSON(uri, function(data){
console.log(JSON.stringify(data));
});
or
add dataType: "json"
in the $.ajax()
$.ajax({
url: uri,
type: "GET",
dataType: "json",
success: function(data){
console.log(JSON.stringify(data));
}
});
so it can expect JSON data to be returned from the page.
Now all you need to do is prepare the data on the server side, using json_encode()
$output = array(
"msg" => "This is output",
"data" => array(
"info" => "Spaaaace",
"cake" => "no"
),
array(
"foo",
"bar"
)
);
echo json_encode($output);
//it will look like this before the text is parsed into JSON in Javascript
//{"msg":"This is output","data":{"info":"Spaaaace","cake":"no"},"0":["foo","bar"]}
This is the way to go if you want objects returned from a request.
Solution
Apart from server-side fix with the json_encode()
, this is the solution.
$.getJSON(uri, function(data){
console.log(JSON.stringify(data));
});
Alternative solution
Assuming you want to keep your $.get()
All you need is the text between <body>
and </body>
Here's an example
$.get(uri, function(msg){
var startWith = "<body>",
endWith = "</body>";
var iStart = msg.search(startWith);
var iEnd = msg.search(endWith);
msg= msg.substring(iStart+startWith.length, iEnd)
console.log(msg);
});
And here's a more advanced answer on that one.