使用jQuery Ajax获取单独的PHP变量

You*_*mon 2 html php variables ajax jquery

我的script.jsget_all.php执行请求,该请求有三个输出变量(echo)$all_categories,$all_brands$all_filters.现在我想在index.html中的三个不同区域中操作它们.

我要放置$all_categories<div id="caregories">,$all_brands<div id="vrands">$all_filtesr<div id="filters">.

如何将它们分别放在每个div?我知道如何将所有这些放在一个<div>但不知道如何分别放置每个变量.

的index.php

<?php // Startup ?>

<?php 

    define('APP_PATH', '../');
    define('SYS_PATH', '../system/');
    define('STYLES', 'assets/styles/');
    define('SCRIPTS', 'assets/scripts/');

    require_once SYS_PATH . 'initializers/all.php'; 

?>

<?php // Controller ?>

<?php



?>

<?php // Viewer ?>

<?php template('header'); ?>

<body>

<div id="static_menu">
    <ul>
        <li><a href="#categories">Categories</a></li>
        <li><a href="#brands">Brands</a></li>
        <li><a href="#filters">Filters</a></li>
        <li><a href="#social">Social</a></li>
    </ul>
</div>
<hr>
<div id="categories">
    <ul></ul>
</div>
<hr>
<div id="brands">
    <ul></ul>
</div>
<hr>
<div id="filters">
    <ul></ul>
</div>
<hr>
<div id="social">
    <ul></ul>
</div>
<hr>

</body>

<?php template('footer'); ?>
Run Code Online (Sandbox Code Playgroud)

的script.js

// DOM ready
$(function(){

    // get categories, brands, filters and social
    $.ajax({
        type: "POST",
        url: "get_all.php"
    }).done(function(data){
        // manipulate recieved in three different divs
    })

});
Run Code Online (Sandbox Code Playgroud)

get_all.php

<?php // Startup ?>

<?php 

    define('APP_PATH', '../');
    define('SYS_PATH', '../system/');
    define('STYLES', 'assets/styles/');
    define('SCRIPTS', 'assets/scripts/');

    require_once SYS_PATH . 'initializers/all.php'; 

?>

<?php // Controller ?>

<?php

$result_arr = $category->select_all();
$all_categories = $html->list_anchor_loop($result_arr, 'category');
echo $all_categories

$result_arr = $brand->select_all();
$all_brands = $html->list_anchor_loop($result_arr, 'brand');
echo $all_brands;

$result_arr = $filter->select_all();
$all_filters = $html->list_anchor_loop($result_arr, 'filter');
echo $all_filters;
Run Code Online (Sandbox Code Playgroud)

xbo*_*nez 7

让您的PHP脚本将结果作为JSON对象发送(请参阅参考资料json_encode).

在你的JS中,你会收到一个对象,比如说resp,它有三个属性resp.categories,resp.filtersresp.brands

有关更多详细信息和特异性,请发布一些代码

get_all.php:

$result = array(
  'categories' => $all_categories,
  'brands' => $all_brands,
  'filters' => $all_filters
);

echo json_encode($result);
Run Code Online (Sandbox Code Playgroud)

script.js

$.ajax({
    type: "POST",
    url: "get_all.php",
    dataType : 'json', //specify that data will be returned as JSON
}).done(function(data){
    // use data.categories, data.brands, data.filters here
    // manipulate recieved in three different divs
})
Run Code Online (Sandbox Code Playgroud)