【问题标题】:Unable to send data to php on select box change无法在选择框更改时将数据发送到 php
【发布时间】:2016-07-24 12:20:22
【问题描述】:

在 index.php 页面上,在 html 内我有一个选择框

<select name="selectLanguage" id="selectLanguage" onchange="OnlanguageChange()">
  <option value="">
    Select your Language
  </option>

  <option value="en">
    English
  </option>

  <option value="fr">
    Français
  </option>

  <option value="de">
    Deutsch
  </option>                                             

</select>

希望在我的 php 代码中获取选择框 onchange 的值。

尝试使用 ajax 调用:

$(document).ready(function(){ 
  $("#selectLanguage").change(function(){ 
    var SelectedLanguage = $(this).val(); 
    alert(SelectedLanguage);
    $.ajax({ 
      type: "POST", 
      url: "index.php", 
      data: SelectedLanguage, 
      success: function(result){ 

      }
    });

  });
});

【问题讨论】:

    标签: javascript php jquery ajax


    【解决方案1】:

    $.ajax 需要数据作为对象...

    $.ajax({
      type: "POST",
      url: "index.php",
      data: { language: SelectedLanguage },
      success: function(result) {
    
      }
    });
    

    在 php 中以 $_POST['language'] 访问它

    【讨论】:

    • 您是否已将data: { language: SelectedLanguage }, 添加到您的$.ajax 函数参数中?
    • 尝试使用filter_input( INPUT_POST, 'language' )以避免未设置时出错...
    • 消除了错误。但该值未发送到 php 页面
    • @SalilLambay 您在 Chrome DevTools 中的 Netwroks 中看到了什么?此请求中是否有“表单数据”和“语言”?
    • @ИванПшеницын 网络 cn 中的数据可见“语言:en”,但仍无法在打印过滤器输入(INPUT_POST,“语言”)中获取数据;或 $_POST['language']
    【解决方案2】:
               var formData = {     
                  //get the value of language selected
                   'SelectedLanguage':$("select[name='selectLanguage'] option:selected").val(),
                };
                $.ajax({ 
                type: "POST", 
                url: "index.php",
                //send language to index.php
                data: formData , 
                success: function(result){ 
    
                  }
            });
    

    【讨论】:

    • 请为您的答案添加一些解释。只发布一点代码并不能提供好的答案。
    • 为什么是 $("select[name='selectLanguage'] option:selected")? $(this).val() 是正确的代码。
    • 我想 var SelectedLanguage = $(this).val();正在做与 'SelectedLanguage':$("select[name='selectLanguage'] option:selected").val() 相同的工作......仍然感谢......一种新的方法
    • 即使这给了我在 chrome 开发工具网络中的 formdata,但在 $_POST['language'] 中仍然无法获取数据
    • 更新打印“真”;打印 "
      True
      " ;并添加 var res = language.split('\n')[1]; $("#result").html(res);成功:函数(语言){
    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多