【问题标题】:Ajax function not working when passing one of the variables through parameter, PHP, JAVASCRIPT, AJAX通过参数、PHP、JAVASCRIPT、AJAX 传递变量之一时,Ajax 函数不起作用
【发布时间】:2015-06-17 04:38:00
【问题描述】:

我正在尝试编写一个函数来从 select 语句中获取值,并将值回显到屏幕上。当我将确切的选择名称放在 ajax 函数中时它可以工作,但是当我尝试通过参数传递选择名称时它停止工作。我知道它已成功通过参数,并且我知道这是正确的选择名称,方法是在我测试它时向函数内部的屏幕发出警报。所以我认为实际的问题可能在这一行:

data: { select: $('select[name=theName]').val()},

但我不确定它有什么问题。我在下面有 2 个版本的代码。第一个版本有效,第二个版本无效。第一个版本在参数中具有确切的选择名称,第二个版本通过名为“theName”的参数传递。请看:

ajax.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript"> 

function ajax(url,theName,id) {
alert(theName)
      $.ajax({
           type: "POST",
           url: url,
           data: { select: $('select[name="select1"]').val()},
           error: function(xhr,status,error){alert(error);},
           success:function(data) {
             document.getElementById( id ).innerHTML = data;
           }

      });

}

</script>

测试1

<?php

echo "<select name = 'select1' onchange = 'ajax(\"test2.php\",\"select1\",\"output\")'>";

?>

^---这个版本有效。

ajax.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript"> 

function ajax(url,theName,id) {
alert(theName)
      $.ajax({
           type: "POST",
           url: url,
           data: { select: $('select[name=theName]').val()},
           error: function(xhr,status,error){alert(error);},
           success:function(data) {
             document.getElementById( id ).innerHTML = data;
           }

      });

}

</script>

测试1

<?php

echo "<select name = 'select1' onchange = 'ajax(\"test2.php\",\"select1\",\"output\")'>";

?>

^---这个版本不行。

【问题讨论】:

    标签: javascript php jquery ajax


    【解决方案1】:

    你在这里省略了双引号和连接:

    data: { select: $('select[name="'+theName+'"]').val()},
    

    【讨论】:

    • 好答案。如果我也想传入类型怎么办?我不想在里面选择,而是想通过名为 type 的参数传递类型。我这样尝试过,但没有成功: data: { select: $('type[name="'+theName+'"]').val()},
    • 没有type这样的输入。名称只是选择元素的一个属性。阅读 CSS 选择器。
    • 不,我的意思是喜欢那种类型。如您所知,选择、输入、单选按钮、复选框。那些类型。
    • 哦,我明白了:data: { select: $(type+'[name="'+theName+'"]').val()},
    【解决方案2】:
    data: { select: $('select[name=' + theName + ']').val()},
    

    【讨论】:

    • 好答案。如果我也想传入类型怎么办?我不想在内部进行选择,而是想通过名为 type 的参数传递类型。我这样尝试过,但没有成功: data: { select: $('type[name='+theName+']').val()},
    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 2017-04-14
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多