AJAX练习

2018-11-13  本文已影响0人  OrangeQjt
一. 2018-11-09_163517.png

1.jd.sql

SET NAMES UTF8;
DROP DATABASE IF EXISTS jd;
CREATE DATABASE jd CHARSET=UTF8;
USE jd;
create table product(
pid INT PRIMARY KEY AUTO_INCREMENT,
pname VARCHAR(13),
pic VARCHAR(12),
price float(4,2),
produceDate date
);
INSERT INTO product VALUES(NULL,'张三','img/1.jpg','23.00','2018-11-9');
INSERT INTO product VALUES(NULL,'李四','img/2.jpg','33.00','2018-11-9');
INSERT INTO product VALUES(NULL,'王五','img/3.jpg','43.00','2018-11-9');
select * from product;

2.product_add.php

<?php
    $pname=$_REQUEST['pname'];
    $pic=$_REQUEST['pic'];
    $price=$_REQUEST['price'];
    $produceDate=$_REQUEST['produceDate'];
    $conn=mysqli_connect('localhost','root','','jd',3306);
    $sql="set names utf8";
    mysqli_query($conn,$sql);
    $sql="insert into product values(NULL,'$pname','$pic','$price','$produceDate')";
    $result=mysqli_query($conn,$sql);
    if($result===true){
        echo 'succ';
    }else{
        echo 'err';
    }

3.product_add.html

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title></title>
    </head>

    <body>
        <p>pname:<input type="" name="" id='pname'></p>
        <p>pic:<input type="" name="" id='pic'></p>
        <p>price:<input type="" name="" id='price'></p>
        <p>prodate:<input type="" name="" id='prodate'></p>
        <p><input type="button" name="" value='保存' id='btn'></p>
        <script type="text/javascript">
            btn.onclick = function() {
                var p = pname.value;
                var c = pic.value;
                var r = price.value;
                var d = prodate.value;
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function() {
                    if(xhr.readyState === 4) {
                        if(xhr.status === 200) {
                            doResponse(xhr);
                        }
                    }

                }
                xhr.open('post', `product_add.php`, true);
                //修改请求消息头部
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.send(`pname=${p}&pic=${c}&price=${r}&prodate=${d}`);
            }

            function doResponse(xhr) {
                if(xhr.responseText === 'succ') {
                    alert('插入成功');
                } else if(xhr.responseText === 'err') {
                    alert('插入失败');
                } else {
                    alert('不可识别的响应消息');
                }
            }
        </script>
    </body>

</html>
二. 2018-11-12_151811.png
上一篇下一篇

猜你喜欢

热点阅读