通过HTTP响应从节点传递Jquery函数

时间:2017-03-24 13:54:16

标签: javascript jquery node.js express http-get

我正在使用基于Node(Express)的API,根据请求,它会将一些HTML和jQuery传递给前端,后端嵌入到文档中。我正在寻找一种巧妙的方法来对后端的函数进行字符串化,以便我可以将它发送到前端。我正在尝试最小化我必须放在前端的代码量。这就是我现在所拥有的功能,但感觉有点难看并且难以调试。

   responseData.scripts = "<script>";
var search_request =
    "$('#search_form').submit(function(event) { "+
            "event.preventDefault();"+
        "data.stage = 'search';"+
        "data.query.first_name='Bob';"+   

        "$.ajax({"+
                "type: 'GET',"+
                "url: 'http://159.203.131.150:3000',"+
            "data:data,"+
            "crossDomain: true,"+
            "success: function(response) {"+
                "response = JSON.parse(response);"+
                "console.log(response);"+
            "}"+            
        "})" +
    "})" +
 "</script>";
 responseData.scripts+=search_request;

在前端,我有

  $.ajax({
 type: "GET",
 url: "http://159.203.131.150:3000",
 data: data,
 crossDomain: true,   

 success: function(response) {
   response = JSON.parse(response);
   $(response.html).prependTo("#content");
   $(response.scripts).appendTo("body");
 },   


  });

2 个答案:

答案 0 :(得分:0)

喜欢这个

$.ajax({
 type: "GET",
 url: "http://159.203.131.150:3000",
 data: data,
 crossDomain: true,   

 success: function(response) {
   response = JSON.parse(response);
   $(response.html).prependTo("#content");
   $(function () {
      $('<script>')
        .attr('type', 'text/javascript')
        .text(response.scripts)
        .appendTo('body');
   })
 }   
});

并从服务器端响应中删除脚本标记

答案 1 :(得分:0)

我找到了一个Express功能来执行此操作(我是Express的新手,它是一个非常基本的功能)。我最终将javascript文件存储在公共文件夹中,并从我的应用程序中提供。

https://expressjs.com/en/starter/static-files.html