JS to jQuery to the fullest
I have this:
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var nocache = 0;
function insert() {
document.getElementById('insert_response').innerHTML = "To Sek .. "
var bID= encodeURI(document.getElementById('bID').value);
var kommentar= encodeURI(document.getElementById('kommentar').value);
nocache = Math.random();
http.open('get', 'insert.php?bID='+bID+'&kommentar=' +kommentar+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('insert_response').innerHTML = response;
if ($("#box[value=1]").length > 0) { window.parent.showMessage("Video Is OK"); }
}
}
And i want to "shorten" the code, and make it use jQuery to the fullest. eg, i have 开发者_StackOverflow社区heard of serialize(); instead of using http.open etc.., but how should i use it in this case?
And do i really need all that in createobject() to make the http?
Untested, but I'm pretty sure this is what you need:
function onInsertComplete(data,textstatus){
$("#insert_response").html(data);
}
function doInsert(){
$("#insert_response").html("To Sek...");
var nocache = '0';
var data = { bID : $("#bID").val(), kommentar: $("#kommentar").val(), nocache: nocache };
$.get('insert.php', data, onInsertComplete);
if ($("#box[value=1]").length > 0) {
window.parent.showMessage("Video Is OK");
}
}
Most of this can be cleaned up with a call to the get method in jQuery.
First, it will abstract away the browser-specific details for you, so you don't have to check how get XMLHttpRequest.
You can then use jQuery to get elements through selectors. To select any element by id, you would use the following syntax:
$("#<id>")
The hashtag indicates that you want to select the elements with the id specified. From there you can use some of the general attribute functions to get the values inside of specific elements.
Finally, you can use Javascript's ability to generate closures to create and pass one as the callback to the get function, which is executed when the call completes. You would then use the same selectors general attribute functions to change the values on the client side when the call completes.
Something on this line?
http://api.jquery.com/load/
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
精彩评论