JavaScript $(document).on('cl-6ren">
gpt4 book ai didi

javascript - 如何在 JavaScript/Ajax 调用中从 HTML 获取变量

转载 作者:行者123 更新时间:2023-11-27 23:17:39 26 4
gpt4 key购买 nike

我正在使用 Zend Framework 2。我想知道如何在我的 javascript 代码中获取以 html 定义的数据。

html

<tr class="MyClass" data-MyData="<?php echo json_encode($array);?>">

JavaScript

$(document).on('click','.MyClass', function () {

var temp =document.getElementsByClassName("data-MyData");

$.ajax({
url: path_server + "pathDefinedInMyConfig",
type: 'post',
encode: true,
dataType: 'json',
data: {
'temp ': temp
},
success: function (data) {
//some code
},
error: function () {
alert("ERROR");
}
});
});

问题是我无法在我的 Controller 方法中访问行。我想访问在我的 Controller 中以 html 定义的我的 $array。

最佳答案

问题是您试图通过名称data-MyData 来查找,但是您“想要”查找的对象是“MyClass”

尝试类似var temp =document.getElementsByClassName("MyClass").attr("data-MyData");

更好的是,由于您使用 MyClass 单击对象,您可以使用 $(this).attr('data-MyData');

然后结果将如下所示:var temp = $(this).attr('data-MyData');

关于javascript - 如何在 JavaScript/Ajax 调用中从 HTML 获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42433739/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com