简体   繁体   English

使用JSON和AJAX从数据库中提取信息

[英]Extracting information from database using JSON and AJAX

I'm trying to make a simple "search" box using Javascript, AJAX, php and JSON. 我正在尝试使用Javascript,AJAX,php和JSON创建一个简单的“搜索”框。 For this project, I'm just using the database "world" I downloaded from mqsql website. 对于这个项目,我只是使用从mqsql网站下载的数据库“world”。 I'm running into a problem when trying to extract the information from my database. 我在尝试从数据库中提取信息时遇到了问题。 It just takes the first line of information and then I get this error: "SCRIPT5007: SCRIPT5007: Unable to get property 'Continent' of undefined or null reference ajaj.js (65,3)" 它只需要第一行信息,然后我收到此错误:“SCRIPT5007:SCRIPT5007:无法获取未定义或空引用的属性'Continent'ajaj.js(65,3)”

Thanks in advance for any help you are able to give me! 在此先感谢您能给我的任何帮助!

Here is my ajaj.js code: 这是我的ajaj.js代码:

var ajaxRequest=new XMLHttpRequest();
var input;
var button;

function init(){
    input = document.getElementById('search');
    input.addEventListener("keyup", sendRequest, false);
    button = document.getElementById('sendButton');
    button.addEventListener("click", sendSecondRequest, false);
}


function sendRequest(){
    ajaxRequest.onreadystatechange = getRequest;

    var searchTxt = "country=" + input.value;

    ajaxRequest.open("GET", "getCountries.php?" + searchTxt, true);
    ajaxRequest.send();
}


function getRequest(){
    if (ajaxRequest.readyState==4 && ajaxRequest.status==200){
        var jsonObj = JSON.parse(ajaxRequest.responseText);

        var dataList = document.getElementById('countries');

        dataList.innerHTML="";

        for(var i = 0; i<jsonObj.length; i++){

            var option = document.createElement('option');

            option.value = jsonObj[i]['Name'];

            dataList.appendChild(option);
        }
    }
}

function sendSecondRequest(){
    ajaxRequest.onreadystatechange = getSecondRequest;

    var infoCountry = "country=" + input.value;

    ajaxRequest.open("GET", "getCountries2.php?" + infoCountry, true);
    ajaxRequest.send();
}

function getSecondRequest(){
    if (ajaxRequest.readyState==4 && ajaxRequest.status==200){
        alert(ajaxRequest.responseText);
        var jsonObj2 = JSON.parse(ajaxRequest.responseText);




        document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>";
        document.getElementById("result2").innerHTML = "LANDSKOD: " + jsonObj2[2]["Continent"] + "<br>";
        document.getElementById("result3").innerHTML = "LANDSKOD: " + jsonObj2[7]["Population"] + "<br>";

    }
}

window.addEventListener("load",init,false);

It's here where the problem lies, I just don't know how to get it to work: 这就是问题所在,我只是不知道如何让它发挥作用:

document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>";
document.getElementById("result2").innerHTML = "LANDSKOD: " + jsonObj2[2]["Continent"] + "<br>";
document.getElementById("result3").innerHTML = "LANDSKOD: " + jsonObj2[7]["Population"] + "<br>";

I've tried a few different solutions but I can't get it working, I've tried to combine the code into one line using: 我尝试了一些不同的解决方案,但我无法使其工作,我尝试将代码组合成一行使用:

document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>" + "Continent: " + jsonObj2[2]["Continent] + "<br>"; 

but that doesn't seem to work for me either. 但这对我来说似乎也不起作用。

Rest of my code: 我的其余代码:

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>AJAX</title>
    <script type="text/javascript" src="ajaj.js"></script>
</head>
<body>
<h1>Sök information om ett land</h1>

<input type="text" list="countries"  id = 'search' placeholder="Land">
<datalist id="countries">
</datalist>
<button type="button" id="sendButton">Hämta information</button>

<p id="result"></p>
<p id="result2"></p>
<p id="result3"></p>

</body>
</html>

getCountries.php getCountries.php

<?php
include_once('db.inc.php');

$country = $_GET['country'];

// Kör frågan mot databasen world och tabellen country
$stmt = $db->prepare("SELECT * FROM country WHERE Name Like ? ORDER BY Name");
$stmt->execute(array("$country%"));

$tableRows = array();

// Lägger resultatet i vår array
$tableRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Här konverteras och skickas resultatet i JSON-format
echo json_encode($tableRows);
?>

getCountries2.php getCountries2.php

<?php
include_once('db.inc.php');

$country = $_GET['country'];

// Kör frågan mot databasen world och tabellen country
$stmt = $db->prepare("SELECT * FROM country WHERE Name Like ? ORDER BY Name");
$stmt->execute(array("$country"));

$tableRows = array();

// Lägger resultatet i vår array
$tableRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Här konverteras och skickas resultatet i JSON-format
echo json_encode($tableRows);
?>

db.inc.php db.inc.php

<?php

define ('DB_USER', 'root');
define ('DB_PASSWORD', 'Abc12345');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'world');

$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';
$db = new PDO($dsn, DB_USER, DB_PASSWORD);
?>

EDIT: I just got the answer from the comments, the information is on the same row, not different, therefore it didn't work with 编辑:我刚刚从评论中得到答案,信息是在同一行,没有不同,因此它不起作用

jsonObj2[2]["Continent"]

but it did work with 但确实有效

jsonObj2[0]["Continent"]

Thank you @sean! 谢谢@sean!

It means that jsonObj2[2] isnt object. 这意味着jsonObj2 [2]不是对象。 It seems like you dont have 3 rows (jsonObj2[2]) in database return array. 看起来你在数据库返回数组中没有3行(jsonObj2 [2])。 Try 尝试

jsonObj2[0]["Code"] + jsonObj2[0]["Continent"] + sonObj2[0] 
["Population"]

It should work but dont know why you target to rows 0,2,7. 它应该工作但不知道为什么你的目标是行0,2,7。

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

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