我正在学习Javascript(主要使用JQuery),并且想知道是否有人可以帮助我。

我写了一条if / else语句,检查是否在URL中出现了特定的字符串,然后根据字符串将表单内容发布到特定的php脚本中。

问:我正在使用的代码有效,但感觉笨拙且不必要地冗长! -我认为必须有一种更简单的方式来撰写!!我环顾四周,但大多数答案似乎都提供了没有任何帮助我理解它是如何完成的代码。

我想要实现的是:

  • 用户填写4种注册表单之一(prereg1.html,prereg2.html,prereg3.html,prereg4.html)
  • 根据URL,if / else语句将表单数据发送到相应的PHP脚本(add_prereg1.php,add_prereg2.php等),该脚本将数据添加到电子邮件列表数据库(由 Activity 监视器托管)

  • 注意:我的php知识也很差-因为 Activity 监视器列表每个都有唯一的ID,所以我可以使php在正确的列表中发布表单数据的唯一方法是拥有4个单独的'prereg.php'脚本。我敢肯定有一种方法可以使php脚本根据javasscript传递的变量来确定要发布到哪个列表,但是在这个阶段,这超出了我的范围!任何指针欢迎。

    无论如何,这里是if / else语句:
        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) {
                       $.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
                            });
                        }
                    }
                }
            }
    

    谢谢你的帮助。

    最佳答案

    考虑一下:

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

    现场演示: http://jsfiddle.net/4MWDm/

    您只需在字符串中搜索序列“prereg”后跟一个数字。括号捕获数字,因此您可以使用[1]访问它。

    顺便说一句使用window.location而不是document.location



    资料来源:https://developer.mozilla.org/en/DOM/document.location

    09-25 16:45
    查看更多