将PHP文件中的数据传递给JSON格式的JS文件

时间:2017-11-23 01:42:32

标签: javascript php jquery json ajax

我正在尝试在网页上构建一个小程序,该程序显示带有汽车品牌的drop-down列表输入类型(在这种情况下为FordBMW)。选择完成后,用户点击提交按钮并在表单下方,特定于该品牌的模型列表将显示在结果div中。

我收到了4个文件:

的index.php:

<form id="form">
  <label for="make">
            Make
            <select name="make" id="make">
                <option value="" selected="selected">None</option>
                <option value="Ford">Ford</option>
                <option value="BMW">BMW</option>
            </select>
        </label>
  <input name="submit" value="submit" type="submit" id="submit">
</form>
<div id="results">
</div>
<script src="js/main.js"></script>

data.php:

<? php

function data() {
  $data = array(
    array(
      'make' => 'Ford',
      'model' => 'Fiesta'
    ),
    array(
      'make' => 'Ford',
      'model' => 'Focus'
    ),
    array(
      'make' => 'Ford',
      'model' => 'Mustang'
    ),
    array(
      'make' => 'BMW',
      'model' => '320'
    ),
    array(
      'make' => 'BMW',
      'model' => 'X3'
    ),
    array(
      'make' => 'BMW',
      'model' => 'X5'
    ),
  );
}

ajax.php:

<?php
require_once( 'data.php' );
$data      = data();
$json_data = array();

和main.js:

$(document).ready(() => {

  var run_ajax = function() {
    results = $('#results');

    $.ajax({
      type: 'post',
      url: 'ajax.php',
      data: formData,
      dataType: 'json',
      beforeSend: function() {

      },
      success: function(response) {

      },
    });
  }

  $('#submit').on('submit', function(e) {
    e.preventDefault();

    run_ajax();
  });

});

如何从data.php访问main.js中的数据?我很欣赏对可能的彻底解释。提前谢谢。

4 个答案:

答案 0 :(得分:1)

看到您提供的代码只需连接它们即可完成所有操作,但首先您需要将data.php文件更改为以下内容

<?php
function data() {
return array(
    array(
        'make'  => 'Ford',
        'model' => 'Fiesta'
    ),
    array(
        'make'  => 'Ford',
        'model' => 'Focus'
    ),
    array(
        'make'  => 'Ford',
        'model' => 'Mustang'
    ),
    array(
        'make'  => 'BMW',
        'model' => '320'
    ),
    array(
        'make'  => 'BMW',
        'model' => 'X3'
    ),
    array(
        'make'  => 'BMW',
        'model' => 'X5'
    ),
);}

然后将您的ajax.php文件改为以下

  <?php
   require_once( 'data.php' );
   $data      = data();
    $make   =   $_POST['make'];

    // print_r($data);exit;
foreach($data as $car){
    if(in_array($make,$car)){
        $filtered[]=$car;
    }
}
 echo json_encode($filtered);

然后将main.js功能更改为以下

$(document).ready(() => {
    var run_ajax = function () {
        results = $('#results');
        $.ajax({
            type: 'post',
            url: 'ajax.php',
            data: $("form").serialize(),
            dataType: 'json',
            beforeSend: function () {},
            success: function (response) {
                for (var key in
                        response) {
                    $("#results").append(" <div > Make: " + response[key]['make'] +
                        ", Model:" + response[key]['model'] + " </div>");
                }
            },
        });
    }
    $('#form').on('submit', function (e) {
        e.preventDefault();
        run_ajax();
    });
});

希望排除

修改

实际上,我们必须发送选择的下拉列表选中的make并过滤掉具有相同品牌的汽车以便回复并显示在下面的div中,必须在ajax.php文件中更改一些内容

答案 1 :(得分:0)

您的data()函数必须首先return数组:

function data(){
    $data = array('key'=>'value'); 
    return $data;
}

然后echoprint() json_encoded数组:

$data = data();
echo json_encode($data); 

答案 2 :(得分:0)

首先,你不需要在data.php文件中定义一个函数,因为它包含在ajax.php文件中,任何可以访问的变量

<强> data.php:

<? php
$data = array(
  array(
    'make' => 'Ford',
    'model' => 'Fiesta'
  ),
  array(
    'make' => 'Ford',
    'model' => 'Focus'
  ),
  array(
    'make' => 'Ford',
    'model' => 'Mustang'
  ),
  array(
    'make' => 'BMW',
    'model' => '320'
  ),
  array(
    'make' => 'BMW',
    'model' => 'X3'
  ),
  array(
    'make' => 'BMW',
    'model' => 'X5'
  ),
);

ajax.php文件从data.php文件中读取数据,过滤数组并将所选make的模型放入新数组并以json字符串形式回显

<强> ajax.php:

<?php
require_once('data.php');
$filtered_make = [];
$make = $_POST['make'];
foreach ($data as $car) {
  if (strtolower($make) == strtolower($car['make'])) $filtered_make[] = $car['model'];
}

echo json_encode($filtered_make);

<强>的index.php:

<form id="form">
  <label for="make">
    Make
    <select name="make" id="make">
      <option value="" selected="selected">None</option>
      <option value="Ford">Ford</option>
      <option value="BMW">BMW</option>
    </select>
  </label>
  <input name="submit" value="submit" type="submit" id="submit">
</form>
<div id="results">
</div>
<script src="http://www.izivote.com/res/js/jquery.min.js"></script>
<script src="js/main.js"></script>

onsuccess,在main.js文件中,从ajax.php返回的json对象中返回的模型列表放在一个列表中并显示在结果容器中

<强> main.js:

$(document).ready(() => {

var run_ajax = function() {
results = $('#results');
var formData =  $('#form').serialize();

$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {

},
success: function(response) {
var resultHTML = "<ul>";
  for(var index in response){
  resultHTML += "<li>" + response[index] + "</li>";
  }
  resultHTML += "</ul>";
results.html(resultHTML);
},
});
}

$('#form').on('submit', function(e) {
e.preventDefault();

run_ajax();
});

});

我希望这会有所帮助

答案 3 :(得分:-1)

data()作为数组返回。 然后将$data编码为json。

<?php
require_once( 'data.php' );
$data      = data();
$json_data = json_encode(array());

和ajax:

$.ajax({
        type: 'post',
        url: 'ajax.php',
        data: formData,
        dataType: 'json',
        beforeSend: function() {

        },
        success: function( response ) {
           console.log(response); // check the return result
           $.each(response, function(key, val){
              $("#results").append("<div>Make:"+key+" , Model:"+val+"</div>");
           });
        },
        error: function (msg) {
           alert("Error: check console");
           console.log(msg);
        }
    });

未经测试但希望有所帮助