仅使用 JavaScript 对象数组创建小型可搜索数据库。没有 AJAX,没有 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13610731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:16:10  来源:igfitidea点击:

Creating a small searchable database with JavaScript Object Arrays only. No AJAX, no PHP

javascriptdatabase

提问by Subjective Effect

I want to create a small database, or collection, of items - only about 30 - you can search with JavaScript alone.

我想创建一个小型数据库或项目集合 - 只有大约 30 个 - 您可以单独使用 JavaScript 进行搜索。

For example - let's say I have 20 houses to rent and I want students to be able to search for them houses with 4 or 5 rooms.

例如 - 假设我有 20 所房子要出租,我希望学生能够搜索有 4 或 5 个房间的房子。

I can create the house objects like this:

我可以像这样创建房屋对象:

function house(address, rooms, bathrooms){
this.address=address;
this.rooms=rooms;
this.bathrooms=bathrooms;
}

var property1 = new house("10 Park Way","4","1");
var property2 = new house("61 Park Avenue", "5","2");
var property3 = new house("585 Park Road", "3", "1");

I want to be able to search this list by "rooms" and display the address, number of rooms and number of bathrooms.

我希望能够通过“房间”搜索此列表并显示地址、房间数量和浴室数量。

NB: I know the way I've written it isn't an Array but I will use an Array so I can use a for loop to cycle through the properties and evaluate them in the following way:

注意:我知道我编写它的方式不是数组,但我将使用数组,因此我可以使用 for 循环来循环遍历属性并按以下方式评估它们:

if(property[i].rooms == roomquery){
    document.write('Address:' + property[i].address + '.<p>');        
    document.write('Address:' + property[i].rooms + '.<p>');
    document.write('Address:' + property[i].bathrooms + '.<p>');
}

Simple eh?

简单吧?

Except I don't know how to pass the roomquery variable from my form to my script.

除了我不知道如何将 roomquery 变量从我的表单传递到我的脚本。

The order of the process is: Search Page -> Results Page -> Details Page

流程顺序为:搜索页->结果页->详情页

The user searches and gets a list of results. There is the option to view the property in more detail on the result page, passing the data from the results to page to be reformatted on a details page. Of course there will be much more data about each property in the Array and I can give this data to the id or value properties of invisible tags for collection and resubmission to a script on the details page.

用户搜索并获取结果列表。可以选择在结果页面上更详细地查看属性,将数据从结果传递到要在详细信息页面上重新格式化的页面。当然,关于 Array 中每个属性的数据会更多,我可以将这些数据提供给不可见标签的 id 或 value 属性,以便收集并重新提交到详细信息页面上的脚本。

I know I can do this with PHP, and I know I could do this by sending the roomquery variable to a script on the same page and making the changes on the Search Page.

我知道我可以用 PHP 做到这一点,我知道我可以通过将 roomquery 变量发送到同一页面上的脚本并在搜索页面上进行更改来做到这一点。

But what I want to do is send the data, which is just a single number, to a script on the Results Page using GET, or any other method, because that way I can run the search from any page that will send to the Search Page.

但是我想要做的是使用 GET 或任何其他方法将数据(只是一个数字)发送到结果页面上的脚本,因为这样我可以从将发送到搜索的任何页面运行搜索页。

I've searched the internet for this and I'm not coming up with anything. There must be a way.

我已经在互联网上搜索过这个,但我没有想出任何东西。一定有办法。

采纳答案by Brad Koch

Since you are working with a static list of houses entirely on the client side, you can accomplish this on a single page with a small amount of basic Javascript. No form submission required.

由于您完全在客户端处理房屋的静态列表,因此您可以使用少量基本 Javascript 在单个页面上完成此操作。无需提交表格。

  1. Set up your basic HTML form, with a place to display the results:

    <form>
        <select name="rooms"></select>
    </form>
    <div id="results"></div>
    
  2. Write some javascript to listen for the change event (this example uses jQuery), do a search, and output the results:

    var houses = [/* ... */]
    $('select[name=rooms]').on('change', function () {
        var rooms = $('select[name=rooms]').val();
    
        $('#results').empty();
    
        for (var i = 0; i < houses.length; i++) {
            if (houses[i].rooms == rooms) {
                $('#results').append('<p>Address: ' + houses[i].address + '</p>');
            }
        }
    });
    
  1. 设置您的基本 HTML 表单,并在其中显示结果:

    <form>
        <select name="rooms"></select>
    </form>
    <div id="results"></div>
    
  2. 编写一些 javascript 来侦听更改事件(此示例使用 jQuery),进行搜索并输出结果:

    var houses = [/* ... */]
    $('select[name=rooms]').on('change', function () {
        var rooms = $('select[name=rooms]').val();
    
        $('#results').empty();
    
        for (var i = 0; i < houses.length; i++) {
            if (houses[i].rooms == rooms) {
                $('#results').append('<p>Address: ' + houses[i].address + '</p>');
            }
        }
    });
    

You can get a lot fancier and add more structure than this, but that should cover the basics.

您可以变得更漂亮并添加更多结构,但这应该涵盖基础知识。

If your heart is set on including a page submission, you can retrieve a parameter from the query string by parsing window.location.search. I think it's a better experience to keep it to one page though.

如果您想包含页面提交,您可以通过解析window.location.search. 不过,我认为将其保留在一页上会更好。

回答by LeandroCR

Why don't you use JSON, here is an example:

为什么不使用 JSON,这里是一个例子:

var json = {
    "house": [{
            "address": "10 Park Way",
            "num1": 4,
            "num2": 1},
        {
            "address": "61 Park Avenue",
            "num1": 5,
            "num2": 2},
        {
            "address": "585 Park Road",
            "num1": 3,
            "num2": 1}]

};

var houses = json["house"];
for(var i=0; i < houses.length; ++i) {
    var houses_i = houses[i];
    if(houses_i["address"] == '10 Park Way') {
        alert('Found WAY!!!');
        break;
    }
}

回答by Lyn Headley

You just need to call your search function from an onchange event:

您只需要从 onchange 事件调用您的搜索功能:

<script type="text/javascript">
function search(roomquery) {
// put your for loop here
}
</script>

rooms: <select onchange="search(this.options[selectedIndex].text);">
    <option>1</option>
    <option>2</option>
</select>?

see fiddle: http://jsfiddle.net/H9jkd/

见小提琴:http: //jsfiddle.net/H9jkd/

回答by Halcyon

Not a full answer but have you considered using Web SQL? This allows you to do SQL queries on data that you've imported in JavaScript.

不是完整的答案,但您是否考虑过使用 Web SQL?这允许您对在 JavaScript 中导入的数据执行 SQL 查询。

回答by sargant

You can parse values out of a request querystring with a simple function such as the ones described here.

您可以使用一个简单的函数(例如此处描述的函数)解析请求查询字符串中的值。

In order to create the querystring, you can have a form with a hidden input:

为了创建查询字符串,您可以有一个带有隐藏输入的表单:

<form action="myresultspage.html" method="get">
    <input type="hidden" id="property" name="property" value="" />
    <input type="submit" />
</form>

Your JS can write to the hidden variable using something like document.getElementByid('property').value = newValue. On submitting this form, you'll be redirected to the URL myresultspage.html?property=newValue.

您的 JS 可以使用类似document.getElementByid('property').value = newValue. 提交此表单后,您将被重定向到 URL myresultspage.html?property=newValue