Home  >  Article  >  Web Front-end  >  Jquery requests NodeJS through ajax to return json data instance

Jquery requests NodeJS through ajax to return json data instance

高洛峰
高洛峰Original
2016-12-07 14:12:041321browse

Recently I read about NodeJS and checked the applications combined with AJAX on the Internet. I feel that the application prospects are quite good. Why use this combination?

1. NodeJS does not need to be installed, you can just copy it and use it, and the environment variables can only be configured in the current cmd window, making it easy to run.

2. Through HTML ajax request, data can be obtained across different domains on different servers.

3. The communication data format is flexible and can be xml, json, binary, etc. The data is suitable for any platform.

Let’s talk about my environment. I am using a computer provided by the company, which has many restrictions. For example, it is a computer in a domain and has low operating permissions. It cannot install any software, cannot modify the computer configuration, cannot use USB flash drives, etc. So I configured a green version of nodejs environment myself, which can only run the nodejs-related environment in the current cmd window; I cannot set up an html server, so I created a separate html file on the D drive and double-clicked it to open it.

Write a script for node execution. The script file app.js is as follows:

var http = require("http");
var fs = require("fs");
 
var str='{"id":"123",name:"jack",arg:11111}';
 
function onRequest(request, response){
 console.log("Request received.");
 response.writeHead(200,{"Content-Type":'text/plain','charset':'utf-8','Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});//可以解决跨域的请求
 //response.writeHead(200,{"Content-Type":'application/json',   'Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});
 //response.write("Hello World 8888\n");
  
 str=fs.readFileSync('data.txt');
 response.write(str);
 response.end();
}
 
http.createServer(onRequest).listen(8888);
 
console.log("Server has started.port on 8888\n");
console.log("test data: "+str.toString());

The data.txt and the current app.js file are placed in the same directory. The code in data.txt is data in json format :{"id":"123",name:"jack",arg:321,remark:"test data"}

Run it through node app.js, and then you can let html access the data through ajax.

The other is the html file I created. The content of the file aaa.html is as follows:

<!DOCTYPE html>
<html>
<head>
 <title>Node JS 实例</title>
 
<script src="jquery-1.4.4.min.js"></script>
 
<script>
 
/*
 
//可用于检查出错函数的错误内容,一般使用$.get()和$.post()函数就可以了
 
$.ajax({
 url: "http://127.0.0.1:8888/",
 type: "GET",
 dataType: "binary", //因为是调用nodeJS返回的json数据,所以必须使用binary类型
 error: function(XMLHttpRequest, textStatus, errorThrown){
 var s1=XMLHttpRequest;
 var s2=textStatus;
 var s3=errorThrown;
 alert("error message : "+errorThrown.toString())
 },
 success: function(data){
 $("#feeds").html(data);
 var dataObj=eval(&#39;(&#39;+data+&#39;)&#39;);//转换为json对象
 $("#id").html("编号:"+dataObj.id);
 $("#name").html("姓名:"+dataObj.name);
 $("#arg").html("年龄:"+dataObj.arg);
 $("span").html(dataObj.remark);
  
// alert( "Data is : " + data );
 }
 
});
 
*/
 
 
//$.get("test.cgi", function(data){ alert("Data Loaded: " + data); }); //$.get函数形式结构
 
$.get("http://127.0.0.1:8888/" + new Date().getTime(), function(data){
$("#feeds").html(data);
var dataObj=eval(&#39;(&#39;+data+&#39;)&#39;);//转换为json对象
$("#id").html("编号:"+dataObj.id);
$("#name").html("姓名:"+dataObj.name);
$("#arg").html("年龄:"+dataObj.arg);
 
$("span").html(dataObj.remark);
 
//alert("Data Loaded: "+new Date().getTime());
});
 
 
 
 
</script>
 
 
 
</head>
<body>
  
 <div id="feeds"></div>
 <div id=id></div>
 <div id=name></div>
 <div id=arg></div>
  
 <span>ddddd</span>
 
</body>
</html>

There are corresponding comments in the file, which will not be explained here. The jquery js file used in it is itself Go to the Internet to download one, and also put it in the directory of the current html file.

A little explanation: When I downloaded versions 1.8.3 and 2.1.4 of jquery, an error was reported. The support for json may not be very good. Version 1.4.4 can run normally, and other versions have not been tested.

The normal display on my local machine and intranet test is as follows:

{"id":"123",name:"jack",arg:32100, remark:"test data"}
Number: 123
Name: jack
Age: 32100
test data

The above environment was tested by myself. I hope it will be helpful to everyone’s learning. Please support the PHP Chinese website


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn