简体   繁体   English

将div的innerHTML设置为从MySQL数据库检索到的信息(使用AJAX / PHP)?

[英]Setting the innerHTML of a div to information retrieved from a MySQL database (using AJAX/PHP)?

On my page (index.php), I have a content-editable div with id = "name" and a content-editable div with id = "info". 在我的页面(index.php)上,我有一个ID为“ name”的内容可编辑div和一个ID为“ info”的内容可编辑div。 I also have a button with id = "save" and a button with id = "lookUp". 我也有一个ID =“ save”的按钮和一个ID =“ lookUp”的按钮。

in index.php : index.php中

<p> <div> Name: </div> <div id="name" contenteditable="true"> </div> </p>
<p> <div> Info: </div> <div id="info" contenteditable="true"> </div> </p>

<p>
    <button id="save" type="button" style="float: left;" class="buttonText"> Save </button>
    <button id="lookUp" type="button" style="float: left;" class="buttonText"> Look Up </button>
</p>

I would like the page to be able to do two things: 我希望页面能够执行以下两项操作:

1) If the user clicks the 'Save' button and both content-editable divs are filled, the name and info entered into the content-editable divs by the user are saved to a two-column table (columns: "name" and "info") in a local MySQL database. 1)如果用户单击“保存”按钮,并且两个内容可编辑的div均被填充,则用户在内容可编辑的div中输入的名称和信息将保存到两列表格中(列:“名称”和“ info”)在本地MySQL数据库中。 I have already implemented this functionality with AJAX/PHP, and it works without error. 我已经使用AJAX / PHP 实现了此功能 ,并且可以正常工作。

2) If the user clicks the 'Look Up' button, then I would like the text entered into the content-editable div with id = "name" (the innerHTML of the name div) to be looked up in the database. 2)如果用户单击“查找”按钮,那么我希望在数据库中查找输入到内容可编辑div中且ID为“ name”(name div的innerHTML)的文本。 If the name is found, I would like the site to retrieve the text stored in the corresponding entry's 'info' column and enter it into the content-editable div with id = "info" (set the innerHTML of the 'info' div to the retrieved info). 如果找到了名称,我希望该站点检索存储在相应条目的“ info”列中的文本,并将其输入到id =“ info”的内容可编辑div中(将'info'div的innerHTML设置为检索到的信息)。

So far I have partially implemented 2) with the following code: 到目前为止,我已经使用以下代码部分实现了2)

in index.php : index.php中

<script type="text/javascript">
    $(document).ready(function(argument) 
    {
        $('#lookUp').click(function()
        {
            $name = $('#name').html();
            $info = $('#info').html();

            $.ajax(
            {
              url: 'lookup.php', type: 'post', data: {nameSubmit: $name}, datatype: 'html', success: function(rsp){alert(rsp);}
            });
        });
    });
</script>

in lookup.php : lookup.php中

<?php 

    $name = $_POST['nameSubmit'];
    $name = mysql_real_escape_string($name);

    $connect = mysql_connect( "localhost", "localUserName", "localPassword", "" );
    $selectedDB = mysql_select_db("nameInfoDatabase", $connect);

    $lookup = "SELECT * FROM nameInfoTable";
    $lookupResults = mysql_query( $lookup, $connect );

    $nameFound = FALSE;

    while($record = mysql_fetch_array($lookupResults))
    {
        if( $record['name'] == $name )
        {
            $nameFound = TRUE;
            $info = $record['info'];
        }
    }   

    if( $nameFound ){ echo "Account Located.  Info: " . $info; }
    else{ echo "FAILURE: Name not found!"; }

    // NOW WHAT?
?>

After a "Look Up" button-click, the information I want to be saved to the innerHTML of the div with id = "info" in index.php is saved to the variable $info in lookup.php. 单击“查找”按钮后,我要保存到index.php中id =“ info”的div的innerHTML中的信息将保存到lookup.php中的变量$ info中。 This $info is correctly printed (echoed) to the dialogue pop-up, but I want it to be entered into the content-editable, id = "info" div of the index.php page. 此$ info已正确打印(回显)到对话框弹出窗口,但我希望将其输入到index.php页面的内容可编辑的id =“ info” div中。 How do I proceed? 我该如何进行?

I have tried things like echoing lines of javascipt, as is discussed here and here , but I have not been able to get it working with existing StackOverflow Q&As. 我已经尝试过像在这里这里讨论的那样回显javascipt行,但我无法使其与现有的StackOverflow Q&A一起使用。 I am sorry if this question is overly basic or has already been addressed in a way that I did not understand, I am very new to PHP and back-end development. 很抱歉,如果这个问题过于基础或已经以我不理解的方式得到了解决,那么我对PHP和后端开发还是陌生的。

Thanks for the help! 谢谢您的帮助! Jack 插口

To properly use this data with JS you can send it in native JSON format. 要在JS中正确使用此数据,您可以将其以本机JSON格式发送。 lookup.php lookup.php

<?php
// here connection and escaping stuff
$lookup = "SELECT * FROM nameInfoTable WHERE name='".$name."' LIMIT 1";
$lookupResults = mysql_query( $lookup, $connect );
// no $nameFound or while loop needed
if (mysql_num_rows($lookupResults) == 1) { // one result obtained
    echo json_encode(mysql_fetch_array($lookupResults)); // fetch and send
}
else {
    // you can do nothing, just don't send anything and response will be empty
    // that's how you can understand that "name" was not found
}
?>

in index.php improve youк ajax success function: 在index.php中改善youja ajax成功功能:

success: function (rsp) {
    if (rsp) { // if data not empty
        var data = JSON.parse(rsp); // parse recieved data 
        $('#info').html(data.info); // properties' names are exactly as columns in your table or like query aliases
    }
}

EDIT Some suggestions that don't really answer your question but may be helpful 编辑一些建议并不能真正回答您的问题,但可能会有所帮助

  1. Try to use mysqli instead of mysql. 尝试使用mysqli代替mysqli It's already deprecated and this a good start to learn object oriented syntax 它已被弃用,这是学习面向对象语法的良好起点

  2. You're escaping post var - it's very good, but you don't check whether it exists neither on client-side (if ($name) { // do ajax request }) nor on back-end if (!empty($_POST['nameSubmit'])) { // do all other stuff } 您正在转义post var-这很好,但是您不检查它是否既不在客户端(if ($name) { // do ajax request })也不在后端if (!empty($_POST['nameSubmit'])) { // do all other stuff }

  3. I don't think you need so much variables, also some coders prefer another style of preparing queries. 我认为您不需要那么多变量,而且一些编码人员更喜欢另一种准备查询的样式。

  4. Actually you need only info from your table, not all * 实际上,您只需要表中的info ,而不是全部*

I'll try to show this all in one piece of code: 我将尝试在一段代码中展示所有这些内容:

if (!empty($_POST['nameSubmit'])) { // check post variable
    // establish connection
    $mysqli = new mysqli("localhost", "localUserName", "localPassword", "nameInfoDatabase");
    // prepare query, sprintf is a little bit easier to read 
    $query = sprintf("SELECT info FROM nameInfoTable WHERE name='%s' LIMIT 1", mysql_real_escape_string($_POST['nameSubmit']));
    // query, actually you can put sprintf here
    $result = $mysqli->query($query);
    // result will have 0 or 1 in property here
    if ($result->num_rows) {
        // php Array("info"=>"...") will be converted to {"info": "..."} for JS
        echo jscon_encode($result->fetch_assoc());
    }
}

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

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