栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将数据从JQuery AJAX请求发送到Node.js服务器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将数据从JQuery AJAX请求发送到Node.js服务器

为了使’data’事件在node.js服务器端触发,您必须对数据进行POST。也就是说,“数据”事件仅响应POST数据。指定“
jsonp”作为数据格式会强制执行GET请求,因为jsonp在jquery文档中定义为:

“ jsonp”:使用JSONP加载JSON块。添加一个额外的“?callback =?” URL的末尾以指定回调

这是修改客户端以触发数据事件的方式。

客户:

<html><head>    <script language="javascript" type="text/javascript" src="jquery-1.8.3.min.js"></script></head><body>    response here: <p id="lblResponse">fill me in</p><script type="text/javascript">$(document).ready(function() {    $.ajax({        url: 'http://192.168.0.143:8080',        // dataType: "jsonp",        data: '{"data": "TEST"}',        type: 'POST',        jsonpCallback: 'callback', // this is not relevant to the POST anymore        success: function (data) { var ret = jQuery.parseJSON(data); $('#lblResponse').html(ret.msg); console.log('Success: ')        },        error: function (xhr, status, error) { console.log('Error: ' + error.message); $('#lblResponse').html('Error connecting to the server.');        },    });});</script></body></html>

一些有用的行可帮助您调试服务器端:

服务器:

var http = require('http');var util = require('util')http.createServer(function (req, res) {    console.log('Request received: ');    util.log(util.inspect(req)) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)    util.log('Request recieved: nmethod: ' + req.method + 'nurl: ' + req.url) // this line logs just the method and url    res.writeHead(200, { 'Content-Type': 'text/plain' });    req.on('data', function (chunk) {        console.log('GOT DATA!');    });    res.end('callback('{"msg": "OK"}')');}).listen(8080);console.log('Server running on port 8080');

节点端数据事件的目的是建立主体-它对单个http请求触发多次,对于它接收的每个数据块都触发一次。这是node.js的异步特性-
服务器在接收数据块之间执行其他工作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483235.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号