在选择的不同单选按钮上调用不同的URL表单JavaScript

时间:2015-05-15 13:06:05

标签: javascript php html

有没有办法可以根据所选的单选按钮从java脚本向不同的php网址发送数据。

示例:

Html 

选择了html单选按钮 然后只从JavaScript中调用 html.php

CSS

选择css radiobutton

然后只调用 CSS.php

HTML。

<div>Choose option:</div>
<input type="radio" name="user_options" value="css" /> CSS 
<input type="radio" name="user_options" value="jquery" /> jQuery 
<input type="radio" name="user_options" value="html" /> HTML
<input type="radio" name="user_options" value="php" /> PHP

脚本到php

<script type="text/javascript">
    $(document).ready(function () {
        $("#submit").click(function () {
            var datahtml = $('input[type="radio"]:checked').val();
            if ($('input[type="radio"]:checked').length == "0") {
                alert("Select any value");
            }
            else {
                $.ajax({
                    type: "POST",
                    url: "html.php",
                    data: "htmldata=" + htmldata,
                    success: function () {
                        $("#msg").addClass('bg');

                    }
                });
            }
            return false;
        });
    });
</script>

2 个答案:

答案 0 :(得分:0)

嗯,这实际上是一个想法,但我并不是说这是完美的。

你可以做的是,对于每个按钮,通过点击它来存储你应该达到的URL,例如:

<input type="radio" name="user_options" data-url="http://example.org/css" value="css" /> CSS 
<input type="radio" name="user_options" data-url="http://example.org/jquery" value="jquery" /> jQuery 
<input type="radio" name="user_options" data-url="http://example.org/html" value="html" /> HTML
<input type="radio" name="user_options" data-url="http://example.org/php" value="php" /> PHP

如您所见,我们为每个按钮添加了一些自定义属性以存储其目标。然后,在dataHtml之后的click事件处理程序中,您可以执行以下操作:

var remoteUrl=$('input[type="radio"]:checked').data("url");

然后替换

url: "html.php",

通过

url: remoteUrl,

您可能需要调整一些名称,但这是一个想法。

希望它会帮助你

答案 1 :(得分:0)

您可以将url变量放入变量,并使用对象文字映射来填充值。您只需确保考虑所有可能的情况或提供默认网址。否则,该URL将是未定义的。下面的例子(注意:我没有测试过,但这应该给你一般的想法)。

$(document).ready(function(){
  $("#submit").click(function(){

    // this is your object map. just make sure that you account 
    //for all of the values, otherwise you'll throw an error. 
    var urls = {
      'css': 'css.php', 
      'html': 'html.php'
    };

    var datahtml = $('input[type="radio"]:checked').val();

    if($('input[type="radio"]:checked').length == "0") {
      alert("Select any value");
    } else {
      $.ajax({
        type: "POST",
        url: urls[datahtml], //this is your variable that pulls from the urls object
        data: "htmldata="+htmldata,
        success: function() {
           $("#msg").addClass('bg');
        }
      });
     }
    return false;
  });
});