[英]Call Different URL Form JavaScript on Different Radio button selected
有没有一种方法可以根据选定的单选按钮将数据从java脚本发送到不同的php url。
例:
Html
选中html单选按钮,然后仅从 JavaScript调用html.php
和
CSS
CSS单选按钮被选中
然后只调用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>
好吧,这实际上是个主意,但我并不是说这是完美的。
对于每个按钮,您可以做的是存储通过单击它应到达的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,
您可能需要改编一些名称,但这是个主意。
希望对你有帮助
您可以使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;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.