【问题标题】:Passing two variables from php to ajax using dropdown使用下拉菜单将两个变量从 php 传递到 ajax
【发布时间】:2016-01-08 07:46:17
【问题描述】:

如何将这两个值(过滤器和 $user_id)传递给 Ajax?

PHP:

$user_id = 3; 
echo "<select name=\"filter\" data-userid=\"".$user_id."\"
onchange=\"getPoints(this.value)\">
<option value=\"one\">One</option>
<option value=\"two\">Two</option>
</select>"; 

AJAX

function getPoints(filter)
{
    var userid = $(this).attr('data-userid');

$.ajax({
type: "GET",
url: 'http://website.com?user_id='+userid,
data: '&action='+filter,
success: function(result){
$("#Target").html(result);
}
});
};

我想得到这个网址:

http://website.com?user_id=3&action=one

我在将 $user_id 传递给 Ajax 时遇到问题。 提前谢谢你。

【问题讨论】:

  • 给出一个id来选择控件并尝试通过jaquery,ajax动态追加

标签: php ajax onchange


【解决方案1】:

你的代码应该是这样的

function getPoints(filter)
{
    var userid = $(this).attr('data-userid');

    $.ajax({
        type: "GET",
        url: 'http://website.com',
        data: {action: filter, user_id: user_id},
        success: function (result) {
            $("#Target").html(result);
        }
    });
}

或者如果我谈论你的方式,那么它应该是

function getPoints(filter)
{
    var userid = $(this).attr('data-userid');

    $.ajax({
        type: "GET",
        url: 'http://website.com?user_id='+userid+'&action='+filter,
        success: function (result) {
            $("#Target").html(result);
        }
    });
}

使用data: {action: filter, user_id: user_id} 总是更好,因为它会像对象本身一样对待。

编辑 JS

 function getPoints(filter)
    {
        var user_id = document.getElementById('test_class').getAttribute('data-userid');
        console.log(user_id);
        $.ajax({
            type: "GET",
            url: 'http://website.com',
            data: {action: filter, user_id: user_id},
            success: function (result) {
                $("#Target").html(result);
            }
        });
    }

PHP

$user_id = 3; 
echo "<select id='test_class' name=\"filter\" data-userid=\"".$user_id."\"
onchange=\"getPoints(this.value)\">
<option value=\"one\">One</option>
<option value=\"two\">Two</option>
</select>";

【讨论】:

  • 问题与 (var userid = $(this).attr('data-userid');) 他返回 undefined
  • 我需要使用函数getPoints(filter)。函数的名称对我的项目很重要。您的第一个解决方案不起作用。问题在于返回 userid
【解决方案2】:

试试这样的

function getPoints(filter){
  var userid = $(this).data('userid');

  $.ajax({
  type: "GET",
  url: 'http://website.com?user_id='+userid,
  data: { action:filter, user_id: userid},
  success: function(result){
   $("#Target").html(result);
  }
 });
};

【讨论】:

  • 问题与 (var userid = $(this).attr('data-userid');) 他返回 undefined
  • 我使用 alert('userid: ' + userid);并且 het 返回用户 ID:undefined.
  • @NachoMoço:感谢您的支持
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多