猿问

关于JSON.parse()的问题

//保存数据 
function save(){ 
var contact = new Object; 
contact.user_name = document.getElementById("user_name").value; 
contact.mobilephone = document.getElementById("mobilephone").value; 
contact.company = document.getElementById("company").value; 
var str = JSON.stringify(contact); 
localStorage.setItem(contact.mobilephone,str); 
loadAll();


//查找数据 
function find(){

var search_phone = document.getElementById("search_phone").value;
var name = localStorage.getItem(search_phone);
var mobilephone = localStorage.key(name);
var str = localStorage.getItem(contact.mobilephone); 
var contact = JSON.parse(str);
var find_result = document.getElementById("find_result"); 
find_result.innerHTML = search_phone + "的机主是:" +contact.user_name; 

在查询数据的代码中想要通过JSON.parse()来获取准确的储存在本地上的值,但是那里错误呢?

白衣染霜花
浏览 709回答 4
4回答

千巷猫影

contact对象没有定义,localStorage.key方法乱用你的数据结构里头mobilephone===search_phone,不然localStorage取出来的是null哇,要判断一下的1234567function find(){    var str=localStorage[document.getElementById("search_phone").value];    if(str){        var contact=JSON.parse(str);        document.getElementById("find_result").innerHTML=contact.mobilephone+"的机主是:" +contact.user_name;     }} 

蓝山帝景

<html><body><h2>通过&nbsp;JSON&nbsp;字符串来创建对象</h3><p>text1: <span id="text1"></span><br />text2: <span id="text2"></span><br /></p><script type="text/javascript">var txt = '{"message":"the response was sucessful","type":"success"}';obj =&nbsp;JSON.parse(txt);document.getElementById("text1").innerHTML=obj.messagedocument.getElementById("text2").innerHTML=obj.type</script></body></html>

慕姐8265434

$.ajax({type: "POST",url:"/i/ajax/get_cp_data",success: function(data) {if (data) {var json = $.parseJSON(data);cat_obj.success(json);}}});
随时随地看视频慕课网APP

相关分类

Java
我要回答