how to access database through javascript?

2020-04-16 04:09发布

I am creating one admin page where I have multiple textboxes.when I enter the userid in one textbox I want to display user name in next textbox when admin moves to next text box.for this I can use ajax or javascript? which one will be better?how can I do it through javascript.

8条回答
劫难
2楼-- · 2020-04-16 05:08

Better use Mootools, jQuery, YUI or any other js framework to perform Ajax requests. This will reduce your development time. For more info check apis of jQuery:

http://api.jquery.com/category/ajax/

查看更多
劫难
3楼-- · 2020-04-16 05:09

The first step is to create a PHP script which will send parse-able data to JavaScript. Do not allow JavaScript to pass raw SQL queries to your PHP.

<?php
$sqlGetName = $mysqli->prepare("SELECT id, name FROM users WHERE id=?");
$sqlGetName->bind_param("i", $_GET['id']);
$sqlGetName->execute();

$result = array('success' => false, 'id' => null, 'name' => null);

$sqlGetName->bind_result($result['id'], $result['name']);

if($sqlGetName->fetch()) {
  $result['success'] = true;
}

echo json_encode($result);

Then use JavaScript to fetch the values. The example below uses the MooTools library for simplicity's sake, but could be done with another library or in plain old regular JavaScript.

var jsonRequest = new Request.JSON({url: 'get_user.php',
  onSuccess: function(result) {
    if(result.success) {
      alert(result.id + ': ' + result.name);
    } else {
      alert('Not Found');
    }
  }
});

jsonRequest.get({'id': 3});
查看更多
登录 后发表回答