简体   繁体   English

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

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

I'm beginner in javascript and php. 我是javascript和php的初学者。 I'm passing json data on radio button click to js and then particular radio selection I want to get it and display on html table 我将单选按钮单击上的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"]);
}

From HTML passing radio selected whole json data 从HTML传递的广播中选择整个json数据

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

在此处输入图片说明

Update:: these code is working but because of some reason it was not working ie. 更新::这些代码正在工作,但是由于某种原因它无法工作,即。 radio button is inside foreach loop (not getting whole data from d) and the data-jsondata data attribute is not containing proper format that's why it was not working otherwise its working thanks everyone!! 单选按钮位于foreach循环内(不从d获取全部数据),并且data-jsondata数据属性未包含正确的格式,这就是为什么它无法正常工作的原因,否则谢谢大家! happy coding 快乐编码

This may help you. 这可能对您有帮助。

// 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);
}

Working Example 工作实例

The data-jsondata should be wrapped in quotes data-jsondata应该用引号引起来

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

then, in sendAjaxRequest, be sure to use JSON.parse, as "element" at this place is a string 然后,在sendAjaxRequest中,确保使用JSON.parse,因为此处的“元素”是一个字符串

EDIT: according to https://api.jquery.com/data/#data-html5 the JQuery's data() does the JSON parsing for you already, so you don't have to use JSON.parse() anyway 编辑:根据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