Ajax + Jquery + PHP中的简单代码不起作用

时间:2017-10-02 15:01:27

标签: javascript php jquery html ajax

我正在尝试通过ajax将数组从php发送到js,但无论我做什么,都不要运行。 我确信它一定很简单,但我已经尝试了一切。

<!doctype html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Test</title>
  <link type="text/css" rel="stylesheet" href="styles.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="scriptJS.js"></script>
</head>
<body>
<div>
  <div class="tweets-container">
    <p>Loading</p>
  </div>
</div>
</body>
</html>
$(document).ready(function() {
  var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
    '<h1>Welcome!</h1>' +
    '<div class="seeTweets"><select>';
  var count = 0;

  $.get({
      url: 'scriptPHP.php',
      type: 'GET',
      data: {
        usUsers: 'usuarios'
      },
      success: function(response) {
        contPrincipalLastTwitter += '<option value =' + response + '>' + response + '</option>';
        count++;
      },
      error: function(e) {
        console.log(e.responseType);
      );
    }
  });

  console.log(count); contPrincipalLastTwitter += '</select></div></div>'; $(document.body).append(contPrincipalLastTwitter);
});
<?php
  $test = array('uno'=>'uno', 'dos' => 'dos');
  echo json_encode($test);
?>

我尽可能地减少了它,最初这个被送到了一个班级而且这个班级根据谁调用它而有几个请求。

2 个答案:

答案 0 :(得分:0)

问题是你尝试在两个不同的时间和地点连接相同的字符串(首先在文档准备就绪,其次是在ajax调用的成功中)

js code:

$(document).ready(function() {
  var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
    '<h1>Welcome!</h1>' +
    '<div class="seeTweets"><select id="test-select"></select></div></div>'; 
$(document.body).append(contPrincipalLastTwitter);
  $.get({
      url: 'scriptPHP.php',
      type: 'GET',
      data: {
        usUsers: 'usuarios'
      },
      success: function(response) {console.log(response);
        console.log(response);
        for(var idx in response){
          $('#test-select').append('<option value =' + idx + '>' + response[idx] + '</option>');
        }
      },
      error: function(e) {
        console.log(e.responseType);
     }});  
});

scriptPHP.php

<?php
$test = array('uno'=>'uno', 'dos' => 'dos');
// add header
header('Content-Type: application/json');
echo json_encode($test);

答案 1 :(得分:0)

一个稍微简单的选项

const target = document.querySelector('#target');

$.ajax({
    url: 'script.php',
    dataType: 'JSON',
    success: response => {
        for (let key in response) {
            const option = `<option value="${key}">${response[key]}</option>`;

            target.innerHTML += option;
        }
    },
    error: error => {
        // todo
    }
});