What is faster jQuery.load or jQuery.ajax() when loading HTML from PHP file?
I have PHP file named "content.php" prepared for both kind of requests, just as an example:
<?php
// Id params passed via GET method
$get = $_GET['param'];
switch ($get) {
case "param_value":
?>
<div data-param="<?php echo $get; ?>">
// My HTML content here
</div>
<?php
break;
case default:
break;
}
// Id params passed via POST method
$post = $_POST['param'];
if ($post != "") {
$data['output'] = '
<div data-param="<?php echo $get; ?>">
// My HTML content here
</div>
';
echo json_encode($data);
}
?>
And than I have Javascript file, from which I am making an AJAX call to PHP:
var oWrapper = jQuery("#wrapper"),
// Loading HTML via jQuery.load() function
sParams = jQuery.param({ param: "value" });
oWrapper.load("/content.php?" + sParams, function () {
console.log("content loaded via load()");
});
// Loading HTML via jQuery.ajax() function
jQuery.ajax({
type: "POST",
dataType: "json",
url: "/content.php",
cache: false,
data: { "param": "value" },
success: function (data) {
oWrapper.html(data.output);
console.log("content loaded via ajax()");
}
});
Which way is faster?
Besides the speed of requests and returns, I wish to know which way is better for security of the 开发者_Python百科app?!
Both ways do pretty much exactly the same thing.
Internally, $(selector).load()
uses $.ajax()
to get the data, then $(selector).html()
to set the html of the selected element to the response of the $.ajax()
call.
If you are loading html into an element, use $(selector).load()
because it is more readable. One is just as secure and as fast as the other.
Note: Internally jQuery now uses $.parseHTML()
rather than $(selector).html()
to convert the string to html. This doesn't really change anything though.
I don't know the specifics but I dont't think there is a difference in security. load() and get() are "optimized" versions of ajax() so they will always be faster and better but I don't you or your visitors will ever feel the difference in a query like yours
精彩评论