简体   繁体   English

从PHP返回多个值到JS函数(AJAX / SQL)

[英]return multiple values from PHP to JS function (AJAX/SQL)

I want to have something like a small search engine for the FAQ section on my website. 我想在我的网站上为“常见问题”部分提供一个小型搜索引擎。 All it does is search the SLQ_DB for the term upon pressing a button. 它所做的只是在按下按钮时在SLQ_DB中搜索该术语。

I want to output the question and the answers in two seperate divs. 我想在两个单独的div中输出问题和答案。 Therefore I have $data and $data1 which belong to the divs. 因此,我有属于div的$ data和$ data1。

$('input#name-submit').on('click',function()
{
    var name = $('input#name').val();
    //alert(name);
    if($.trim(name) != "")
    {
        $.post('ajax/name.php',{name:name},function(data, data1)
            {
                $('div#name-data').html(data);
                alert(answer);
                $('div#name-data1').html(data1);

            });
    }
});

But when I hit enter the second div shows "success". 但是,当我按下Enter键时,第二个div显示“成功”。 But the first one has data and data1 in it. 但是第一个中有data和data1。 When I write function(data1, data) in the js file, the data1 has all the information, and data is just "success". 当我在js文件中写入function(data1,data)时,data1拥有所有信息,而data只是“成功”。

What's happening here? 这里发生了什么事?

The echo function in PHP outputs the content of a variable to the response body. PHP中的echo函数将变量的内容输出到响应主体。 This body is a "string" that your web application receives. 该正文是您的Web应用程序接收到的“字符串”。

Let's say you have a code like this: 假设您有这样的代码:

<?php
$var1 = "hello";
$var2 = "world";
echo $var1;
echo $var2;
?>

The resulting response body will look like this: helloworld . 结果响应主体将如下所示: helloworld

Now let's say this is your JS code: 现在,这是您的JS代码:

$.post('ajax/name.php',{name:name},function(data) {
    console.log(data); // "helloworld"
});

jQuery will pass the response body to the data variable, which now contains heloworld . jQuery会将响应主体传递给data变量,该变量现在包含heloworld

You need to somehow separate the individual variables inside the response body, eg using JSON. 您需要以某种方式分离响应主体内的各个变量,例如使用JSON。

First step is to encode the data on the server, that's as simple as that: 第一步是在服务器上编码数据,就这么简单:

<?php
echo json_encode(["var1"=>$var1, "var2"=>$var2]);
?>

This will create a response body that looks like this: {"var1":"hello","var2":"world"} . 这将创建一个响应主体,如下所示: {"var1":"hello","var2":"world"}

The next logical step is to decode this JSON using JavaScript: 下一步的逻辑步骤是使用JavaScript解码此JSON:

$.post('ajax/name.php',{name:name},function(data) {
    var res = JSON.parse(data);
    console.log(res.var1); // "hello"
    console.log(res.var2); // "world"
});

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

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