[英]Moved code into a function. Now doesn't work. What's wrong?
First a huge code block followed by the actual question. 首先是一个巨大的代码块,然后是实际的问题。
$(document).ready(function(){
// debug. takes an object as argument and prints its content
function printObject(o) {
var out = '';
// for (var p in o) {
// out += p + ': ' + o[p] + '\n';
// }
for (var p in o) {
if (!o.hasOwnProperty(p)) out += '(inherited) ';
out += p + ': ' + o[p] + '\n';
}
alert(out);
}
function makeDialogTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
function sendData(is_okay) {
// if all form fields have been filled out
if (is_okay == 1) {
$.ajax({
type: "GET",
url: "/cgi-bin/ajax.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
// generate and send parameters to server-side script
data: $(this).serialize(),
// script call was *not* successful
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
}, // error
// script call was successful
// result contains the JSON values returned by the Perl script
success: function(result){
if (result.error) { // script returned error
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
$('div#create_result').text("result.success: " + result.success + ", result.id: " + result.id);
$('div#create_result').addClass("success");
} //else
} // success
}); // ajax
} else { // if (is_okay) { ...
$('div#create_result').text("Submission cancelled. Changes have not been saved.");
$('div#create_result').addClass("error");
} // if/else
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// required for $(this) to work for save bottons
$('form').live('submit', function(){
var title = this.elements.title.value;
var owner = this.elements.owner.value;
var users = this.elements.users.value;
var groups = this.elements.groups.value;
var begin_date = this.elements.from.value;
var end_date = this.elements.to.value;
var anchor = this.elements.anchor.value;
// get selected radio button using name instead if ID
var type = $(this).find('input:radio[name="ctype"]:checked').val() || '';
// check value
var is_okay = 0;
if (title == '') {
alert('Title is required');
} else if (!(/[A-Za-z0-9]|\s/.test(title))) {
alert('Illegal characters in title. Only a-z A-Z and space is allowed');
} else if (owner == '') {
alert('Owner is required');
} else if (!(/[A-Za-z]|,/.test(owner))) {
alert('Illegal characters in owner. Only a-z A-Z and , is allowed');
} else if (begin_date == '') {
alert('Begin Date is required');
} else if (!(/\d{2}\/\d{2}-\d{4}/.test(begin_date))) {
alert('Illegal characters in Begin Date. Format must be: dd/mm-yyyy');
} else if (end_date == '') {
alert('End Date is required');
} else if (!(/\d{2}\/\d{2}-\d{4}/.test(end_date))) {
alert('Illegal characters in End Date. Format must be: dd/mm-yyyy');
} else if (type == '') {
alert('Type is required');
} else if (type == "individuel" && groups != '') {
alert('Groups are not allowed for individuel');
} else if (type == "individuel" && users == '') {
alert('Users is required');
} else if (type == "individuel" && groups == '' && !(/[A-Za-z]|,/.test(users))) {
alert('Illegal characters in users. Only a-z A-Z and , is allowed');
} else if (type == "course" && users != '') {
alert('Users are not allowed for course');
} else if (type == "course" && groups == '') {
alert('Groups is required');
} else if (type == "course" && users == '' && !(/[A-Za-z]|,/.test(groups))) {
alert('Illegal characters in groups. Only a-z A-Z and , is allowed');
} else {
is_okay = 1;
}
// if all form fields have been filled out
// send the form data for varification and look up display names and show in a confirm box
if (is_okay == 1) {
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
// generate and send parameters to server-side script
data: $(this).serialize(),
// script call was *not* successful
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
alert("Error occured in ajax.js confirm code. Report this to mj@imm.dtu.dk");
}, // error
// script call was successful
// result contains the JSON values returned by the Perl script
success: function(result){
if (result.error) { // script returned error
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
// decode JSON string into arrays
var users = $.parseJSON(result.users);
var owners = $.parseJSON(result.owners);
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-confirm").dialog({
resizable: false,
height: 600,
modal: true,
open: function() {
$(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
},
buttons: {
Okay: function() {
$(this).dialog("close");
sendData(1);
},
Cancel: function() {
is_okay = 0;
$(this).dialog("close");
sendData(0);
}
} // buttons
}); // dialog
} //else
} // success
}); // ajax
} else { // if (is_okay) { ...
$('div#create_result').text("Fill out the form to create an activity");
$('div#create_result').addClass("error");
is_okay = 0;
} // else
// // if all form fields have been filled out
// if (is_okay == 1) {
// $.ajax({
// type: "GET",
// url: "/cgi-bin/ajax.pl",
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// // generate and send parameters to server-side script
// data: $(this).serialize(),
// // script call was *not* successful
// error: function(XMLHttpRequest, textStatus, errorThrown) {
// $('div#create_result').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", errorThrown: " + errorThrown);
// // extract error message
// // var pattern = new RegExp(": \"(.+)\"}");
// // var match = pattern.exec(XMLHttpRequest.responseText);
// // $('div#create_result').text(match[1]);
// $('div#create_result').addClass("error");
// }, // error
// // script call was successful
// // result contains the JSON values returned by the Perl script
// success: function(result){
// if (result.error) { // script returned error
// $('div#create_result').text("result.error: " + result.error);
// $('div#create_result').addClass("error");
// } else { // perl script says everything is okay
// $('div#create_result').text("result.success: " + result.success + ", result.id: " + result.id);
// $('div#create_result').addClass("success");
// } //else
// } // success
// }); // ajax
// } else { // if (is_okay) { ...
// $('div#create_result').text("Fill out the form to create an activity");
// $('div#create_result').addClass("error");
// } // else
$('div#create_result').fadeIn();
return false;
});
});
The same code can be read at 可以在以下位置读取相同的代码
http://pastebin.com/0kXzZGND http://pastebin.com/0kXzZGND
with line numbers. 与行号。
I moved the huge code block from line 205-245 into a function sendData(is_okay)
at line 26-65. 我将巨大的代码块从205-245行移到了26-65行的
sendData(is_okay)
函数中。 The function is called at line 181 and 186. 在第181和186行调用该函数。
The code that I put in the function uses things like $.ajax({
and $(this).
. 我在函数中放入的代码使用
$.ajax({
和$(this).
。
Could this be a problem? 这可能是个问题吗?
If so, how can that be fixed? 如果是这样,如何解决?
Update The code block should update the HTML, but it doesn't do that anymore. 更新代码块应更新HTML,但现在不再这样做。
Update After applying one patrick dw's solutions I get this error: 更新在应用了一个patrick dw的解决方案后,出现此错误:
result is null
and it points to this code 它指向此代码
success: function(result) {
in the newly created function. 在新创建的函数中。
Is it because the GET request now doesn't return anything? 是否因为GET请求现在不返回任何内容?
Your issue is like with $(this).
您的问题就像
$(this).
. 。 If you're just calling a function like normal, the value of
this
will be window
. 如果你只是打电话一样正常的功能,价值
this
将是window
。 I'm guessing you're expecting a DOM element. 我猜您正在期待一个DOM元素。
You can manually set the value of this
in the function you're calling by using the .call
method. 您可以手动设置的值,
this
在你通过调用函数.call
方法。
To do so, call your function as follows: 为此,请按以下方式调用您的函数:
sendData.call( this, 1 );
Another option would be to have your function accept another argument, and use that: 另一种选择是让您的函数接受另一个参数,并使用该参数:
sendData( 1, this );
function sendData(is_okay, el) {
// ...
data: $(el).serialize(),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.