Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在node.js中使用jQuery ajax调用_Javascript_Jquery_Html_Ajax_Node.js - Fatal编程技术网

Javascript 如何在node.js中使用jQuery ajax调用

Javascript 如何在node.js中使用jQuery ajax调用,javascript,jquery,html,ajax,node.js,Javascript,Jquery,Html,Ajax,Node.js,这类似于,但我觉得这个问题没有得到充分的回答 我尝试使用jQuery ajax调用(get、load、getJSON)在页面和node.js服务器之间传输数据。我可以从浏览器中点击地址,看到“你好,世界!”!“,但当我从我的页面尝试此操作时,它失败并显示我没有得到响应。我设置了一个简单的测试页面和hello world示例来测试此操作: <!DOCTYPE html> <html lang="en"> <head> <meta charset="

这类似于,但我觉得这个问题没有得到充分的回答

我尝试使用jQuery ajax调用(get、load、getJSON)在页面和node.js服务器之间传输数据。我可以从浏览器中点击地址,看到“你好,世界!”!“,但当我从我的页面尝试此操作时,它失败并显示我没有得到响应。我设置了一个简单的测试页面和hello world示例来测试此操作:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>get test</title> 
</head>
<body>
    <h1>Get Test</h1>
    <div id="test"></div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
    <script>
        $(document).ready(function() {
            //alert($('h1').length);
            $('#test').load('http://192.168.1.103:8124/');
            //$.get('http://192.168.1.103:8124/', function(data) {                
            //  alert(data);
            //});
        });
    </script>
</body>
</html>

我假设您的html页面托管在不同的端口上。在大多数浏览器中,同源策略要求加载的文件与加载的文件位于同一端口上。

如果您的简单测试页面位于hello world node.js示例之外的其他协议/域/端口上,则您正在执行跨域请求,因此违反了jQuery ajax c所有(获取和加载)都以静默方式失败。若要获取此工作跨域,应使用基于的格式。例如node.js代码:

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);
和客户端JavaScript/jQuery:

$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.1.103:8124/',
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: false,
        timeout: 5000,
        success: function(data) {
            $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);
        }
    });
});

还有其他方法可以让它正常工作,例如完全使用框架设置或构建web应用程序。

感谢yojimbo的回答。为了添加到他的示例中,我想使用jquery方法$.getJSON,它在查询字符串中放入一个随机回调,所以我还想在Node.js中解析它。我还想传回一个对象并使用stringify函数

这是我的客户端代码

$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
  alert(data);
},
function(jqXHR, textStatus, errorThrown) {
    alert('error ' + textStatus + " " + errorThrown);
});
这是我的服务器端Node.js

var http = require('http');
var querystring = require('querystring');
var url = require('url');

http.createServer(function (req, res) {
    //grab the callback from the query string   
    var pquery = querystring.parse(url.parse(req.url).query);   
    var callback = (pquery.callback ? pquery.callback : '');

    //we probably want to send an object back in response to the request
    var returnObject = {message: "Hello World!"};
    var returnObjectString = JSON.stringify(returnObject);

    //push back the response including the callback shenanigans
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);

在服务器端使用类似以下内容:

http.createServer(function (request, response) {
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
        // handle async request
        var u = url.parse(request.url, true); //not needed

        response.writeHead(200, {'content-type':'text/json'})
        response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
    } else {
        // handle sync request (by server index.html)
        if (request.url == '/') {
            response.writeHead(200, {'content-type': 'text/html'})
            util.pump(fs.createReadStream('index.html'), response)
        } 
        else 
        {
            // 404 error
        }
    }
}).listen(31337)

太棒了,谢谢!我将此设置为使用jsonp,正如您的示例中所述,它工作得非常好。回答很好,yojimbo,这确实帮助了我。我发布了一个带有一些额外内容的答案。使用express构建nodejs应用程序将如何解决跨域请求问题?@RunForest:如果应用程序完全构建在express,那么您可能不需要进行跨域请求,因为所有内容都将从同一来源提供。@Petsoukos长轮询(作为一种基于web的推送技术)可以通过几个模块(例如socket.io,它还支持其他传输)在node.js中进行,但是直接轮询MySQL效率很低。我建议查看一些发布/订阅机制,例如可用于此目的的redis机制。我们需要知道正在加载的文件中有什么内容-加载文件中的代码是如何执行的?您的代码工作得很好。请注意,text/pl会出现mime错误将内容类型更改为application/javascript可以解决这个问题。
http.createServer(function (request, response) {
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
        // handle async request
        var u = url.parse(request.url, true); //not needed

        response.writeHead(200, {'content-type':'text/json'})
        response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
    } else {
        // handle sync request (by server index.html)
        if (request.url == '/') {
            response.writeHead(200, {'content-type': 'text/html'})
            util.pump(fs.createReadStream('index.html'), response)
        } 
        else 
        {
            // 404 error
        }
    }
}).listen(31337)