HTML字段;在json_encode-发送到Jquery之后设置PHP数组


HTML Field; set PHP Array after json_encode - Send to Jquery?

我正在html输入字段中用PHP设置一个数组,并最终将该数组发送到jquery函数。

这不起作用,所以我继续使用json_encode并以这种方式发送它。但是,由于我在html字段(名称)中设置它,因此由于字符的原因,它不会呈现。然后我通过使用htmlspecialchars使其工作。

//html php
<input type="checkbox" name="<?php echo htmlspecialchars(json_encode($row)); ?>" />
//jquery
var arr = $('#someAssetDiv input:checkbox:checked').map(function(){
          return $(this).attr('name');
}).get();
console.log(JSON.stringify(arr));
//which sends back what I need but I am applying htmlspecialchars

然而,我的问题是,在jquery方面——在应用htmlspecialchar之前,我如何将其修改回标准对象?

我的最终目标是循环浏览发送的每个对象,并与它们一起跳舞。

Jquery库中是否有我没有找到的内置内容?提前感谢!

由于您没有$row的示例,在这种情况下,我只创建一个示例数据。在这种情况下,您可以使用jQuery的$.parseJSON。输出

<?php
// PHP
$values = array(
    array('id' => 1, 'name' => 'test1'),
    array('id' => 2, 'name' => 'test2'),
);
?>
<!-- form with echoed with json encode -->
<form method="POST">
    <input type="hidden" name="array" value="<?php echo htmlspecialchars(json_encode($values)); ?>" />
    <button type="button" id="button">Test</button>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#button').on('click', function(){
        var json_value = $('input[name="array"]').val();
        json_value = $.parseJSON(json_value);
        console.log(json_value);
    });
});
</script>

但我建议,如果您想在服务器上获得一些数据,请使用$.ajax,然后映射返回值。

如果您需要将php数组转换为javascript,可以尝试使用JSON:

<script>
  var json_arr = JSON.parse("<?php echo json_encode($array) ?>");
  console.log(json_arr);
</script>

然后你可以得到值:

var value = json_arr[0]; //or
var value = json_arr.somekey;

注意:如果你把js放在一个外部文件.js中,你会得到一个错误,因为php代码不能在除.html之外的外部文件上工作,所以把它放在你的html代码中

相关文章: