首页 > 解决方案 > jQuery - 将服务器上的文件内容发布到页面

问题描述

我有一个非常基本的动态 jQuery 搜索函数,它查询一个 json 数组:

<!DOCTYPE html>
<html>
 <head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style>
  #result {
   position: absolute;
   width: 100%;
   max-width:870px;
   cursor: pointer;
   overflow-y: auto;
   max-height: 400px;
   box-sizing: border-box;
   z-index: 1001;
  }
  .link-class:hover{
   background-color:#f1f1f1;
  }
  </style>
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:900px;">
   <h3 align="center">Search ...</h3>   
   <br /><br />
   <div align="center">
    <input type="text" name="search" id="search" placeholder="Search ..." class="form-control" />
   </div>
   <ul class="list-group" id="result"></ul>
   <br />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $.ajaxSetup({ cache: false });
 $('#search').keyup(function(){
  $('#result').html('');
  $('#state').val('');
  var searchField = $('#search').val();
  var expression = new RegExp(searchField, "i");
  $.getJSON('data.json', function(data) {
   $.each(data, function(key, value){
    if (value.name.search(expression) != -1 || value.location.search(expression) != -1)
    {
     $('#result').append('<li class="list-group-item link-class"><img src="'+value.image+'" height="40" width="40" class="img-thumbnail" /> '+value.name+' | <span class="text-muted">'+value.location+'</span></li>');
    }
   });   
  });
 });
 
 $('#result').on('click', 'li', function() {
        $.post("https://123.xyz/endpoint",
    
    -- payload here ---
    
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
   
 });
});

</script>

json 数组以下列格式存储对象:

{
    "name":"Apples",
    "image": "images/apples.jpg",
    "location":"Depot 1, 12",
    "path":"https://123.xyz/data/343r.xml"
  },
  {
    "name":"Oranges",
    "image": "images/oranges.jpg",
    "location":"Depot 1, 13"
    "path":"https://123.xyz/data/331r.xml"
  },

数组中的“路径”对象表示服务器上文件的物理位置。

当用户搜索并单击相关信息时,我想要一个功能将服务器上的平面文件的内容发布到服务器上的另一个端点(即传递 XML 文件 --> https://123.xyz/端点)。

但是,我正在努力弄清楚如何做到这一点。我可以发布 json 格式的数据,但我不知道如何将服务器上已经存在的平面文件的字符串(不使用上传功能)从一个位置传递到另一个位置。

这些文件是 XML 数据——它有点资源密集,但它们可以被读入另一个变量,然后作为字符串发布到端点吗?

非常感谢任何建议。

标签: javascriptjquerypost

解决方案


推荐阅读