繁体   English   中英

如何在单选按钮上单击以获取JSON存储的数据

[英]How to get json stored data on radio button click

我是javascript和php的初学者。 我将单选按钮单击上的json数据传递给js,然后选择特定的单选,我想获取它并显示在html表上

$return_arr=array();
$row_array['firstName']= $row['firstName'];
$row_array['lastName']= $row['lastName'];
$row_array['mobiePhoneNumber']= $row['mobiePhoneNumber'];
$row_array['officePhoneNumber']= $row['officePhoneNumber'];

// here push data into json array
array_push($return_arr,$row_array);

$(".radioBtn").click(function(event){
     e.preventDefault();
     // using data attribute getting data of radio button click (json data)
     sendAjaxRequest(($(this).data("jsondata")));
});

function sendAjaxRequest(element,urlToSend)
{
  // here element has got whole json data but not able to get one by one data
  // I have used JSON.parse(element); but page is not working
  var jsondata = element; 

  alert(jsondata.firstName);   

  //var jsonDataa = $.parse(jsondata);
  alert(jsondata["firstName"]);
}

从HTML传递的广播中选择整个json数据

<input type="radio" id="radioBtn" class="radioBtn" name="radioBtn"
       data-jsondata=<?php echo json_encode($return_arr)?>>

在此处输入图片说明

更新::这些代码正在工作,但是由于某种原因它无法工作,即。 单选按钮位于foreach循环内(不从d获取全部数据),并且data-jsondata数据属性未包含正确的格式,这就是为什么它无法正常工作的原因,否则谢谢大家! 快乐编码

这可能对您有帮助。

// Suppose Your JSON data is {"name":"abcd","age":"22"}  from PHP
<input type="radio" onclick="call(this)" data-jsondata='{"name":"abcd","age":"22"}' /> abc


function call(obj){
   var data = obj.getAttribute("data-jsondata");
   data = JSON.parse(data);
   alert(data.name);
}

工作实例

data-jsondata应该用引号引起来

data-jsondata="<?php echo json_encode($return_arr)?>"

然后,在sendAjaxRequest中,确保使用JSON.parse,因为此处的“元素”是一个字符串

编辑:根据https://api.jquery.com/data/#data-html5 jQuery的data()已经为您完成了JSON解析,因此您无论如何都不必使用JSON.parse()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM