简体   繁体   English

如何发送和接收 ajax 请求而不是从 main.js 文件中抓取代码?

[英]How do I send and receive the ajax request instead of grabbing the code from the main.js file?

I am trying to do a AJAX request with server side Node JS and client side Jquery.我正在尝试使用服务器端 Node JS 和客户端 Jquery 执行 AJAX 请求。

Currently my client-side code looks like this:目前我的客户端代码如下所示:

let theSearchRequest = $("#search").val();

                $.ajax({
                    method:"GET",
                    url:"./main.js",
                    data: theSearchRequest
                })
                .done( (theListOfNames) => {
                    $("#listOfNames").html(theListOfNames);
                });

my server-side code looks like this:我的服务器端代码如下所示:

let request = require("request");

let names = ["ryan", "liam", "john", "james", "michael"];

request.get({
    url:"./index.html",
},
(error, response, body) =>{
    console.log(body);

});

the output is that the "p" tag with the id "listOfNames" shows the server side code.输出是 ID 为“listOfNames”的“p”标记显示服务器端代码。

How do I send and receive the ajax request instead of grabbing the code from the main.js file?如何发送和接收 ajax 请求而不是从 main.js 文件中抓取代码?

You have to pass search input in any specific key您必须在任何特定键中传递搜索输入

let theSearchRequest = $("#search").val();
$.ajax({
    method:"GET",
    url:"./main.js",
    data: {search: theSearchRequest}
})
.done( (theListOfNames) => {
    $("#listOfNames").html(theListOfNames);
});

On server-side, you will get search input in the query string parameter.在服务器端,您将在查询字符串参数中获得搜索输入。

let request = require("request");
let names = ["ryan", "liam", "john", "james", "michael"];
request.get({
    url:"./index.html",
},
(error, response, body) =>{
    console.log(body.query);

});

In your jQuery ajax request you are calling url:"./main.js" which actually is a file (a javascript file).在您的 jQuery ajax 请求中,您正在调用url:"./main.js"这实际上是一个文件(一个 javascript 文件)。

I assume main.js is your server side code, right?我假设main.js是你的服务器端代码,对吧? What you want to do, is to call not main.js but index.html in your ajax request on the client side.您想要做的是在客户端的 ajax 请求中不调用main.js而是调用index.html

On top, you should convert the searchRequest value to a query string and send that to the server.最重要的是,您应该将 searchRequest 值转换为查询字符串并将其发送到服务器。

let theSearchRequest = $("#search").val();
//e.g.
let theSearchRequestQueryString = 'searchRequest=' + theSearchRequest;
$.ajax({
    method:"GET",
    url:"./main.js",
    data: theSearchRequestQueryString
})
.done( (theListOfNames) => {
    $("#listOfNames").html(theListOfNames);
});

I can't tell if this is what you really want to achieve (calling the index.html file).我不知道这是否是您真正想要实现的(调用index.html文件)。

In order to work anyway, the node.js server needs to run.无论如何,为了正常工作,需要运行 node.js 服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM