将代码移动到函数中。现在不起作用。怎么了?

时间:2011-05-17 15:28:38

标签: javascript jquery ajax

首先是一个巨大的代码块然后是实际的问题。

$(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;
    });
});

可以在

读取相同的代码

http://pastebin.com/0kXzZGND

带行号。

我将第205-245行的巨大代码块移动到第26-65行的函数sendData(is_okay)。该函数在第181和186行调用。

我在函数中添加的代码使用$.ajax({$(this).之类的内容。

这可能是个问题吗?

如果是的话,该如何解决?

更新 代码块应该更新HTML,但它不再这样做了。

更新 在应用了一个patrick dw的解决方案后,我收到了这个错误:

result is null

它指向此代码

success: function(result) {

在新创建的函数中。

是因为GET请求现在不返回任何内容吗?

1 个答案:

答案 0 :(得分:3)

您的问题与$(this).类似。如果您只是调用正常的函数,则this的值将为window。我猜你在期待一个DOM元素。

您可以使用this方法在您正在调用的函数中手动设置.call的值。

为此,请按以下方式调用您的函数:

sendData.call( this, 1 );

另一种选择是让你的函数接受另一个参数,然后使用:

sendData( 1, this );

function sendData(is_okay, el) {

   // ...
   data: $(el).serialize(),