Javascript 将代码移动到函数中。现在不';不行。什么';怎么了?

Javascript 将代码移动到函数中。现在不';不行。什么';怎么了?,javascript,jquery,ajax,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 (

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

$(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;
    });
});
它指向这个代码

success: function(result) {
在新创建的函数中


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

您的问题与
$(这是)类似。如果您只是像普通一样调用函数,
this
的值将是
window
。我猜您需要一个DOM元素

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

为此,请按如下方式调用函数:

sendData.call( this, 1 );
另一种选择是让函数接受另一个参数,并使用该参数:

sendData( 1, this );

function sendData(is_okay, el) {

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

您的问题类似于
$(此)。
。如果您只是像普通一样调用函数,
this
的值将是
window
。我猜您需要一个DOM元素

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

为此,请按如下方式调用函数:

sendData.call( this, 1 );
另一种选择是让函数接受另一个参数,并使用该参数:

sendData( 1, this );

function sendData(is_okay, el) {

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

将与您的问题相关的代码放入实际问题中。不需要外部粘贴站点,StackOverflow自己的系统可以很好地格式化代码。Pastebin甚至不是一个实时站点(甚至像jsfiddle.net或jsbin.com这样的实时站点也只是一个问题的附属品,代码本身应该一直是这样的)。@t.J.Crowder:公平地说,代码太多了。@gAMBOOKa:没问题。关键是,SO现在不仅仅是这个人的一种资源;它的目的是为将来有类似问题的其他人提供资源。外部链接可能会以未跟踪的方式被修改、移动、删除等,使问题完全无用。我希望看到这样的行号,但在代码中添加标记并不困难@桑德拉:最好先问一下,让人们知道他们在看什么(很多人甚至都不会看代码块),然后引用你的代码(带标记)。@Sandra:看来你的perl脚本没有返回任何东西。尝试在perl脚本中声明示例数据,并手动运行它,以查看是否获得所需的结果。此外,您是否尝试过使用Chrome的Inspector或Firebug进行调试。可能是脚本路径不正确。请将与问题相关的代码放入实际问题中。不需要外部粘贴站点,StackOverflow自己的系统可以很好地格式化代码。Pastebin甚至不是一个实时站点(甚至像jsfiddle.net或jsbin.com这样的实时站点也只是一个问题的附属品,代码本身应该一直是这样的)。@t.J.Crowder:公平地说,代码太多了。@gAMBOOKa:没问题。关键是,SO现在不仅仅是这个人的一种资源;它的目的是为将来有类似问题的其他人提供资源。外部链接可能会以未跟踪的方式被修改、移动、删除等,使问题完全无用。我希望看到这样的行号,但在代码中添加标记并不困难@桑德拉:最好先问一下,让人们知道他们在看什么(很多人甚至都不会看代码块),然后引用你的代码(带标记)。@Sandra:看来你的perl脚本没有返回任何东西。尝试在perl脚本中声明示例数据,并手动运行它,以查看是否获得所需的结果。此外,您是否尝试过使用Chrome的Inspector或Firebug进行调试。可能是脚本的路径不正确。请澄清,
.call(thisArg,normalArgs)
thisArg
将sendData中的
this
的值更改为指定的值。我已应用了您的第二个解决方案,并更新了问题。我现在得到的
结果是空的
。只是澄清一下,
。调用(thisArg,normalArgs)
thisArg
将sendData中的
this
的值更改为指定的值。我已应用了您的第二个解决方案,并更新了问题。我现在得到的
结果为空。