js处理服务器返回的对象

js处理服务器返回的对象

格式一:
{
firstname:"Bruce",
lastname:"Perry",
gender:"M",
country:"USA"
}

代码片段:

function  handleJson(  ){
    
if (request.readyState  ==   4 ){
        
if (request.status  ==   200 ){
            
var  resp  =   request.responseText;
            
var  func  =   new  Function( " return  " + resp);
            
var  objt  =  func(  );
            
var  div  =  document.getElementById( " json " );
            stylizeDiv(resp,div);
            div 
=  document.getElementById( " props " );
            div.innerHTML
= " <h4>In object form</h4> " +
                          
" <h5>Properties</h5>firstname=  " +
                          objt.firstname 
+ " <br />lastname= " +
                          objt.lastname
+   " <br />gender= " +
                          objt.gender
+   " <br />country= " +
                          objt.country;
        } 
else  {
            alert(
" A problem occurred with communicating between  " +
                 
" the XMLHttpRequest object and the server program. " );
        }
    }
// end outer if
}

 


格式二:

[
 "basketball","football"
]


代码片段:

// event handler for XMLHttpRequest
function  handleResponse() {
    
try{
        
if(request.readyState == 4){
            
if(request.status == 200){
                
var resp =  request.responseText;
              
                
if(resp != null){
                    
//return value is a JSON array
                    var objt = eval(resp);
                    
                    createChecks(objt);
                }

            }
 else {
                
//request.status is 503  if the application isn't available;
                //500 if the application has a bug
                alert(
                        
"A problem occurred with communicating between"+
                        
" the XMLHttpRequest object and the server program.");
            }

        }
//end outer if
    }
 catch (err)   {
        alert(
"It does not appear that the server "+
              
"is available for this application. Please"+
              
" try again very soon. \nError: "+err.message);

    }

}




 

你可能感兴趣的:(js处理服务器返回的对象)