I have made my own jQuery plugin, but it has problem that values I set in form are not found in form when I try to generate query string from form. Test it here http://jsfiddle.net/z3Yff/3/.
(function($) {
$.fn.ajaxSubmit = function( options ) {
// Plugin settings
var settings = {
beforeFunction : function() {},
afterFunction : function() {}
};
// Override options
if ( options ) {
$.extend( settings, options );
}
// Set variables
var self = this;
// Check that form value is set
var checkValue = function(value) {
if(value != undefined && value != null)
{
return true;
}
return false;
};
// Catch submitting input/button
var submitInputName;
$("button, input[type=submit]", this).live("click", function() {
submitInputName = $(this).attr("name");
});
// Submit form
var submitForm = function(form) {
var method = form.attr("method");
if(!checkValue(method) || method.length == 0) method = "post";
var action = form.attr("action");
var query = "";
var i = 0;
$("input, button, textarea", $(this)).each(function(index) {
var name = $(this).attr("name");
var value = $(this).attr("value");
var type = $(this).attr("type");
if(checkValue(value) && checkValue(name))
{
if(i > 0)
开发者_如何学编程 {
query = query + "&";
}
query = query + name + "=" + value;
i++;
}
});
alert(query); // This is empty String, but it should contain values I enterd to form
return $.ajax({
type: method,
cache: false,
url: action,
data: query,
async: false
}).responseText;
};
// Add ajax submit catching
this.submit(function() {
options.beforeFunction();
submitForm($(this));
options.afterFunction();
return false;
});
};
})(jQuery);
Your immediate problem is in your checkValue
function. This conditional will always be false:
if(value != undefined && value != null && name != undefined && name != null)
because you're not passing name
into the function; the above is logically equivalent to this:
var name;
if(value != undefined && value != null && name != undefined && name != null)
Just as a style note, you could write it as:
function checkValue(value) {
return typeof value != 'undefined' && value != null;
}
There is no special undefined
value or keyword in JavaScript. When you say x != undefined
you're actually implicitly creating a variable called undefined
that is not initialized, hence the typeof value != 'undefined'
instead of your value != undefined
.
There are other problems. For one, you're skipping over <select>
elements. For another, you're not checking the type
of <input>
elements so you'll include the values of checkboxes and radio buttons that are in the form but not selected.
Furthermore, you're using the wrong thing in your .each
, you want $(form)
rather than $(this)
so this:
$("input, button, textarea", $(this)).each(function(index) {
should be this:
$("input, button, textarea", $(form)).each(function(index) {
I didn't fix the <select>
, radio button, or checkbox issues but this version is at least producing a query string: http://jsfiddle.net/ambiguous/8QYWH/
精彩评论