2014-11-23 69 views
1

我想在我的节点JS项目中使用AJAX,但运行过程中出现的项目后,我看到了以下错误:如何在节点js中使用ajax?

TypeError: Object function (w) { 
       if (!w.document) { 
        throw new Error("jQuery requires a window with a document"); 
       } 
       return factory(w); 
      } has no method 'ajax' 

我的代码是:

      var jq = require('jquery'); 
         jq.ajax({ 
           type: "POST", 
           url: "http://localhost/sms/index.php", 
          }); 
+1

你为什么要这样做? “在我的nodejs项目中使用ajax”?为什么不使用常规的http请求? 'http:// nodejs.org/api/http.html#http_http_request_options_callback'或者其中一个包装库? – deitch 2014-11-23 13:55:46

+0

你使用的是什么版本的jQuery? 1.x不支持非浏览器环境。 – Shaun 2014-11-23 13:57:07

+0

@deitch因为在http模块中,我必须为我的php文件定义httpd conf,但我只是想在本地主机中调用php文件。当使用http模块时出现错误:{[Error:connect ECONNREFUSED] code:'ECONNREFUSED', errno:'ECONNREFUSED', syscall:'connect'} cd。 – h3dgh 2014-11-23 14:30:26

回答

2

您可以使用request module(NPM安装请求):

var request = require('request'); 
request({ 
    method: 'POST', 
    url: 'http://localhost/sms/index.php', 
    json: someJsonObject 
    // or form depending on what http://localhost/sms/index.php accepts, 
    // see request document for more options 
}, function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    console.log(body) 
    } 
}); 
+1

tnx @Ben,我写下面的代码,但在我的PHP文件$ _POST是空的,什么是错的? var form = { \t number:'test', \t msg:'test', \t}; \t var formData = querystring.stringify(form); \t var contentLength = formData.length; \t REQ({ \t \t头:{ \t '内容长度':CONTENTLENGTH, \t '内容类型': '应用/ X WWW的窗体-urlencoded' \t}, \t URI:的 'http://本地主机:8080/send_sms/index.php的', \t体:FORMDATA, \t方法: 'POST' \t},功能(ERR,RES,体){ \t \t的console.log( 'res是',re或多个); \t \t console.log('err',err); \t}); – h3dgh 2014-11-24 07:42:05

+1

您可能需要为表单数据使用'表单',请尝试form:formData,而不是body:formData。这来自request doc:form - 当传递一个对象或查询字符串时,它将body设置为查询字符串表示形式的值,并添加Content-type:application/x-www-form-urlencoded标头。当传递任何选项时,返回一个FormData实例(并通过管道请求)。请参阅上面的“表单”部分 – Ben 2014-11-25 05:35:31