【问题标题】:Meteor: Make jQuery ajax posts from NodeJs to phpMeteor:从 NodeJs 到 php 制作 jQuery ajax 帖子
【发布时间】:2023-03-11 21:50:02
【问题描述】:

我正在使用this API 在我的流星应用程序中执行 CRUD 数据库操作。到目前为止,每一个操作都执行得很好。

现在考虑一个发生错误的用例(例如,一些验证错误,如无效参数)然后我想通过 jQuery ajax 调用将错误对象发送到 php 脚本。

所以问题是:如何将对象从 NodeJs 脚本发布到 php?

我尝试通过meteor add jquery 添加 Meteor 的默认 jquery 包。然后做了这样的事情:

var $ = require('jquery');
....
....
 function test(data){
   console.log('test'+JSON.stringify(data));
     $.post({
        type: 'POST',
        url: 'http://vibsy.com/test/chest.php',
        data: data,
        success: function(data) {
          console.log(data);
        } 
     });
  }

但这显示了错误:

ReferenceError: require is not defined
    at app\server\collectionapi.js:1:10

有什么想法吗?

【问题讨论】:

    标签: jquery node.js meteor


    【解决方案1】:

    Jquery 在客户端运行良好,我不太确定它是否会在服务器端运行。如果您执行了meteor add jquery,则不必使用require。 Meteor 将自动引用准备使用的正确 js 文件。删除下面的行(仅限客户端),应该很好去

    var $ = require('jquery'); 
    

    如果您的脚本在服务器上运行,它看起来就是这样。最好使用Meteor.http。运行 meteor add http 并使用类似:

    Meteor.http.call("POST", "http://vibsy.com/test/chest.php",{params: data}, function (error, result) {
        if (result.statusCode === 200) {
            console.log(result);
        }
     });
    

    或者更舒服(同步):

    var result = Meteor.http.call("POST", "http://vibsy.com/test/chest.php",{params: data});
    if (result.statusCode === 200) {
        console.log(result.data); //JSON content
        console.log(result.content); //raw content
    }
    

    【讨论】:

    • 我已遵循您的解决方案。 Meteor 控制台显示响应为here。但是 php 端没有活动。我一直在检查 Firebug 中的 Net 面板,但它仍然处于空闲状态。
    • 您必须检查 php 脚本,它返回一个 Hi,所以如果某事没有发生在它那一端。您是否为 post 参数传递了数据中的任何内容?
    • php 端什么都没有。我只想从流星那边收到贴在那里的物体。另外,我已将{params: data} 替换为包含{result: "fail", code:"1001", message: 'Parameter missing'}obj
    • 你需要使用{params: {result: "fail", code:"1001", message: 'Parameter missing'}}
    • 我认为您需要再次查看 PHP 结束,因为它正在使用 Hi 对流星作出响应,这表明请求成功。问题更可能出现在 PHP 端。您不会在 firebug 中看到任何结果,因为它只显示从客户端发送的请求
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多