开发者

Javascript - how to avoid long/ugly if/else statements?

I'm learning Javascript (mainly using JQuery) and was wondering if somebody could help me.

I've written an if/else statement that checks to see if a particular string appears in the URL, then posts a forms content to a particular php script depending on the string.

Q: The code I'm using works, BUT feels clumsy and unnecessarily long! - I figure there MUST be a simpler way to write this!? I've had a look around but most answers just seem to provide code without anything to help me understand how it was done..

What I'm trying to achieve is:

  1. A user completes one of 4 signup forms (prereg1.html, prereg2.html, prereg3.html, prereg4.html)
  2. Depending on the URL, the if/else statement sends the form data to a corresponding PHP script (add_prereg1.php, add_prereg2.php etc.) which adds the data to an email list database (hosted by campaign monitor)

note: My php knowledge is pretty poor too - because the campaign monitor lists each have unique IDs, the only way I can get the php to post the form data in the right list is to have 4 separate 'prereg.php' scripts. I'm sure there is a way to get the php script to figure out which list to post to based on the variables passed by the javasscript but this is a bit beyond me at this stage! Any pointers welcome..

Anyhow here is the if/else statement:

    if (document.location.href.indexOf('prereg1') > -1) {
           $.ajax({
                type: "POST",
                url: "bin/add_prereg1.php",
                data: 'name=' + name + '&email=' + email
            });
        } 

        else {
                if (document.location.href.indexOf('prereg2') > -1) {
           开发者_C百科        $.ajax({
                        type: "POST",
                        url: "bin/add_prereg2.php",
                        data: 'name=' + name + '&email=' + email
                    });
                }

            else {
                if (document.location.href.indexOf('prereg3') > -1) {
                   $.ajax({
                        type: "POST",
                        url: "bin/add_prereg3.php",
                        data: 'name=' + name + '&email=' + email
                    });
                }

            else {
                    if (document.location.href.indexOf('prereg4') > -1) {
                       $.ajax({
                            type: "POST",
                            url: "bin/add_prereg4.php",
                            data: 'name=' + name + '&email=' + email
                        });
                    }
                }                   
            }
        }

Thanks for any help.


Consider this:

var match = window.location.href.match( /prereg(\d)/ );

if ( match ) {
    $.ajax({
        type: 'POST',
        url: 'bin/add_prereg' + match[1] + '.php',
        data: 'name=' + name + '&email=' + email
    });
}

Live demo: http://jsfiddle.net/4MWDm/

You simply search the string for the sequence "prereg" followed by a digit. The parens capture the digit, so you can access it with [1].


Btw use window.location instead of document.location.

document.location was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location instead.

Source: https://developer.mozilla.org/en/DOM/document.location


You could use a for loop:

for (var i = 1; i <= 4; i++) {
    if (document.location.href.indexOf('prereg' + i) > -1) {
        $.ajax({
            type: "POST",
            url: "bin/add_prereg" + i +".php",
            data: 'name=' + name + '&email=' + email
        });

        break;
    }
}       


Almost all statements are the same, so you can generalize.

  • Use the ~ trick - it returns falsy for -1 and thruthy otherwise. This is useful in combination with indexOf.

  • Next, the ?: works like this: a ? b : c returns b if a is truthy and c if a is falsy.

Admittedly, setting the number variable is still kind of repetitive.

var href = location.href, // so that you don't have to
                          // write 'location.href' but only 'href'

    number = ~href.indexOf('prereg1') ? 1
           : ~href.indexOf('prereg2') ? 2 // if the first ~ returned falsy
           : ~href.indexOf('prereg3') ? 3 // etc.
           : ~href.indexOf('prereg4') ? 4 // etc.
           : null; // if all returned falsy

if(number) { // if not null (null is falsy so won't pass the 'if')
    $.ajax({
        type: "POST",
        url: "bin/add_prereg" + number + ".php",  // insert number
        data: 'name=' + name + '&email=' + email
    });
}


Using regular expressions you can simplify it to something like:

document.location.href.match(/prereg(.)/);
var index = RegExp.$1:

$.ajax({
    type: "POST",
    url: "bin/add_prereg" + index + ".php",
    data: 'name=' + name + '&email=' + email
});


No need to have a loop you can get the index from url itself according to your code,

var url=document.location.href;
var startIndex=url.indexOf('prereg'); 
var index=    url.substring(startIndex+5,1);//make sure your index is correct (not tested by me)



 $.ajax({
            type: "POST",
            url: "bin/add_prereg" + i +".php",
            data: 'name=' + name + '&email=' + email
  });


First of all you can simply use else if { ... } instead of else { if { ... } }. The way you're doing things in your code is a little bit too complicated for my taste.

I'd rather write a function that extracts the "prereg" parts from the location string and then wrap up the jQuery $.ajax call after that (this way you wouldn't need to copy the code into all the then-blocks, since the only difference is the URL for the AJAX request).

If you have the string ("prereg1", "prereg2", etc.) extracted correctly, you can also use a switch statement instead of the if/else-cascade. If the URL is the only different it's not really worth doing any kind of flow-control in my opinion.


You can use the switch as known from other programming languages such as PHP as you mentioned

    switch (document.location.href) {
case 'prereg1':
// Your code here
break;

case 'prereg2':
// Your code here
break;

case 'prereg3':
// Your code here
break;

case 'prereg4':
// Your code here
break;
}

It doesn't really help with the rest of your code, which would still be repetitive, but in regards to all of the nested if/else statements, switches are more readable.


if document.location.href.indexOf('prereg') > -1) {   
    $.ajax({
        type: "POST",
        url: "bin/add_" + document.location.href + ".php",
        data: 'name=' + name + '&email=' + email
    });
}


You could use a regular expression to pull the required piece out of the url like this:

var re=new RegExp(/prereg\d/);

var postUrl = 'bin/add_' + re.exec(document.location.href) + '.php';

$.ajax({
        type: "POST",
        url: postUrl ,
        data: 'name=' + name + '&email=' + email
       });


Just grab the number from the html filename, and construct your URL with it:

$.ajax({
                var pagename = location.pathname;
                var formid = pagename.substring(7,10);
                var myurl = "bin/add_prereg" + formid + ".php";
                type: "POST",
                url: myurl,
                data: 'name=' + name + '&email=' + email
            });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜