【问题标题】:Jquery script not showing in firebug or firingJquery 脚本未在萤火虫或触发中显示
【发布时间】:2013-03-19 13:22:42
【问题描述】:

我正在尝试通过使用 jquery/ajax 脚本来获得一个下拉框来更改第二个下拉框。 Firebug 显示 Jquery 正在运行,但我的脚本根本没有显示。

<script type="text/javascript">
        function ajaxfunction(parent)
        {
            $.ajax({
                url: '../functions/process.php?parent=' + parent;
                success: function(data) {
                    $("#sub").html(data);
                }
            });
        }
    </script>

process.php 只是一个 MySQL 查询(有效)

我的初始下拉框由 MySQL 查询填充

<select name="front-size" onchange="ajaxfunction(this.value)">
//Query
</select>

然后第二个下拉框就是

<select name = "front-finish" id="sub">
</select>

我该如何解决这个问题?

【问题讨论】:

  • 你能在 Firebug 中看到你的 ajax 调用吗?控制台有错误吗?
  • 啊我现在做。ReferenceError: ajaxfunction is not defined
  • 看看我的答案,它会为你工作
  • 我认为您对 jQuery 包含有疑问。当它没问题时,ajax 调用将可见并且应该没问题。建议:避免像onchange=... 这样的内联代码。更喜欢使用 jQuery 的 .ready() 方法和 .on('change', callback) 添加 javascript 行为

标签: php jquery mysql ajax firebug


【解决方案1】:

调用内联函数一点都不好……因为 web 2.0 标准建议使用不显眼的 JS 而不是 onevent 属性……看看为什么here.. 其他 thigs .. 使用 ajax 的正确方法是使用类型和数据 ajax 选项在控制器中发送值..

<script type="text/javascript">
    $(function(){
    $('select[name="front-size"').change(function()
    {
        $.ajax({
            url: '../functions/process.php',
            type:'get',
            data:{'value' : $(this).val()}, 
            dataType:"html",   //<--- here this will take the response as html... 
            success: function(data) {
                $("#sub").html(data);
            }
        });
    });
 });
</script>

你的proces.php应该是..

 <?php
   //db query ...thn get the value u wanted.. 
   //loop through it..
   $optVal .= "<option value="someDbValue">some DDB values</option>";
   // end loop

   echo $optValue;exit;

更新

看起来您的选择中仍然有onchange="ajaxfunction(this.value)" this 删除它是不需要的,并且 JavaScript 中的 ajaxfunction 也是...

<select name="front-size" >    
                   //----^ here remove that

【讨论】:

  • 应该像 $optVal。 = "
  • 嗯,我在 firebug 中继续收到“ajaxfunction undefined”错误
  • 看起来你还在调用内联函数..删除它..检查我的更新
【解决方案2】:

使用jQuery.on() 允许我们在动态加载的内容上添加事件。

$('select[name^="front-"]').on('change',function(e){
    e.preventDefault();
    var value = $(this).val();
    ajaxfunction(value);
});

[name^="front-"] 这将选择所有具有namefront- 开头的SELECT 框。

【讨论】:

    【解决方案3】:

    在你的 process.php 中给这样的

    echo "<select name='front-finish' id='sub' onchange='ajaxfunction(this.value)'>";
    

    这样你需要通过ajax在新创建的选择框中添加“onchange”函数

    或者你可以去掉 onchange 函数,写成这样

    $("select[name^='front-']").live('change',function(){
       //Do your ajax call here
    });
    

    【讨论】:

    • 我给了 2 个灵魂,如果他有 2 个或更多选择框,第二个会更好,而且他正在通过 ajax 更新整个选择框....这就是为什么而不是在每个上添加 onchange 事件ajax 调用我建议添加事件....我认为它应该更好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2012-01-18
    • 1970-01-01
    • 2011-05-04
    相关资源
    最近更新 更多