簡體   English   中英

使用AJAX中的數據回復PHP腳本(JSON)

[英]Using data from AJAX Reply to a PHP Script (JSON)

措辭可能有點偏離。 我正在嘗試使用Battle.NET API來檢索有關字符的一些信息。 我有一個“服務器”字段和一個“字符名稱”字段。

我已經審查了一些類似的問題,例如這個問題,也許這只是我的PHP新手,但是我對如何正確地做到這一點感到困惑。 我仍然不確定如何解決PHP錯誤。

我所做的就是設計將HTML + PHP嵌入到一個“ php”文件中。 它工作了 然后,我將它們分離為index.html + test.php, 它起作用了 。主要問題是幾件事-我沒有呈現響應,只是讓它“回顯了”響應。 似乎是在JSON中

 {"lastModified":1477156067000,"name":"Thischaracter","realm":"Thisrealm","battlegroup":"Thisbattlegroup","class":1,"race":6,"gender":0,"level":110,"achievementPoints":20805,"thumbnail":"thrall/50/129432626-avatar.jpg","calcClass":"Z","faction":1,"totalHonorableKills":8657}

因此流程必須是HTML表單-提交-> AJAX-> PHP表單(這是我的“經驗”,因為我從未對響應做任何事情)->可以從PHP數據中獲取getJSON嗎? -> HTML輸出。 我提到AJAX是因為我不希望頁面更新。 只是要更新的“ div”或LI。

index.html-我在此發布之前做了一些修改,以消除多余的廢話。

<form action="testingApiForBnet.php" method="post" id="myForm">
      <p class="inp-wrap search-wrap">
        <label for="search-field" class="search-label grid-25">Find</label>
        <input type="search" name="search-term" id="charSearch" class="grid-75"/></p>
      <p class="inp-wrap cat-wrap">
        <label for="categories" class="grid-20">on</label>
        <select name="search categories" id="servers" class="grid-80">
        </select>
      </p>
      <submit name="SubmitButton">
    </form>

testAPI.php

<?php
if(isset($_POST['SubmitButton']))
 {
 $charName = $_POST['charName'];
  ##$_POST['charName'];
$server = $_POST['servers'];
  ##$_POST['server'];
$bnetAPI = "https://us.api.battle.net/wow/character/";
$apiKey = "apiKeyWouldGoHere";
// Example https://us.api.battle.net/wow/character/$Server/$CharName?locale=en_US&apikey=$apiKey//
$request = $bnetAPI . urlencode($server) .'/'.$charName .'?locale=en_US&apikey=' . $apiKey ;
$response  = file_get_contents($request);
$jsonobj  = json_decode($response);
}
 ?>

我從另一個線程獲得的“ json_decode”和“ file_get_contents”,因為我得到了非對象響應。 有了這些$ jsonobj,我上面鏈接的對象就被釋放了。

test.js

$(document).ready(function () {
$('#myForm').on('submit', function(e) {
  e.preventDefault();
    $.post('testAPI.php', $(this).serialize(), function (data) {
      alert(data);
     console.log(data)
    return false;
    })
});
});

直到“功能(數據)”為止,該腳本實際上是從我成功運行的另一種形式中提取的。 目前,當我單擊“提交”時,什么也沒發生-沒有重定向,沒有響應,沒有console.log-我覺得這是因為我正在發布消息,並且需要進行GET操作,但是我仍然會從數據中獲取“東西”嗎?

將不勝感激任何輸入。 除非我直接運行PHP腳本,否則仍然無法對PHP進行故障排除。 我覺得這僅僅是語言中的功能。

謝謝!

更新Placeholder.php

<?php
if (!empty($_POST)) {
 $charName = $_POST['charName'];
  ##$_POST['charName'];
$server = $_POST['servers'];
  ##$_POST['server'];
$bnetAPI = "https://us.api.battle.net/wow/character/";
$apiKey = "key";
// Example https://us.api.battle.net/wow/character/Thrall/Teodoro?locale=en_US&apikey=$apiKey//
$request = $bnetAPI . $server .'/'.$charName .'?locale=en_US&apikey=' . $apiKey ;
$response  = file_get_contents($request);
$jsonobj  = json_decode($response);
header('Content-Type: application/json');
  echo $response;
  exit();
}
?>

更新index.html(僅JS部分)

$(document).ready(function () {
  $('#myForm').submit(function (e) {
    e.preventDefault();

    $.post('test2.php', $(this).serialize(), function (data) {
     console.log(typeof(data));
      if (typeof data === 'string')
        data = JSON.parse(data);
      if (typeof data !== 'object') {
        console.log("failed to parse data");
        return;
      }
    data = JSON.parse(data);
   console.log(data);
    });
   /*

   */
   console.log('Data is not returning.');
    return false;
  });
});

您的jQuery代碼引用具有myForm ID的表單,但尚未將ID分配給該表單。 因此,您應該添加id屬性,如下所示

<form id="myForm">

接下來,您必須修復發布到的URL。 它應該是testAPI.php ,而不是text.php

$('#myForm').submit(function (e) {
  e.preventDefault();
  $.post('testAPI.php', function (data) {
    // ...
  });
})

由於您要綁定onsubmit並自己處理發布請求,因此您可能不需要表單中的actionmethod屬性。 由於testAPI.php返回JSON內容,因此您需要在請求處理程序中對其進行解碼。 同樣,通過$.post()調用,您不會將任何數據發送到服務器。 這只是一個空的POST請求。 您必須將序列化形式作為第二個參數傳遞:

test.js

$('#myForm').submit(function (e) {
  // note, `this` variable refers to the form node.
  e.preventDefault();
  $.post('testAPI.php', $(this).serialize(), function (data) {
    if (typeof data === 'string')
      data  = JSON.parse(data);
    console.log(data);
  });
  return false;
})

如果是字符串,代碼將解析data 如果響應返回Content-Type: application/json (實際上,它是JSON數據的正確MIME類型),則jQuery處理程序可以將data作為Object傳遞。 因此,我建議您在testAPI.php修復MIME類型,是的,您應該打印響應而不是進行解碼(除非您需要對其進行修改):

header('Content-Type: application/json');
echo $response; // supposed to be a JSON string
exit();

但是,如果您需要修改后的響應,請再次對其進行解碼,修改和編碼:

header('Content-Type: application/json');
$response = json_decode($response, true);
$response['something'] = 'somevalue';
// unset($response['redundant_field']);
header('Content-Type: application/json');
echo json_encode($response); // supposed to be a JSON string
exit();

test.php的

<?php
if (!empty($_POST)) {
  $search_term = $_POST['search-term'];
  $category = $_POST['category'];

  $fake_response = [
    'term' => $search_term,
    'cat' => $category,
    'somethingelse' => date('r'),
  ];

  header('Content-Type: application/json');
  echo json_encode($fake_response);
  exit();
}
?>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>Test</title>
  <script
          src="https://code.jquery.com/jquery-3.1.1.min.js"
          integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
          crossorigin="anonymous"></script>
</head>
<body>
  <form id="myForm">
    <input type="search" name="search-term" id="charSearch"/>
    <select name="category" id="servers">
      <option value="optA" selected>optA<option>
      <option value="optB">optB</option>
    </select>
  <input type="submit" name="SubmitButton"/>
  </form>
  <script>
$(document).ready(function () {
  $('#myForm').submit(function (e) {
    e.preventDefault();

    $.post('test.php', $(this).serialize(), function (data) {
      if (typeof data === 'string')
        data = JSON.parse(data);
      if (typeof data !== 'object') {
        console.log("failed to parse data");
        return;
      }
      console.log(data);
    });
    return false;
  });
});
  </script>
</body>
</html>

示例輸出(在瀏覽器的控制台中)

Object { term: "rr", cat: "optA", somethingelse: "Sun, 23 Oct 2016 05:10:50 +0000" }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM