繁体   English   中英

jQuery和Ajax成功函数-如何从PHP获得响应

[英]jQuery & Ajax success function - how to get response from PHP

我对使用PHP和JavaScript的Ajax真的很陌生。 我必须做一个简单的项目作为培训班,并创建了js脚本:

$(function() {
   $('#bookAdd').submit(function (e) {
       e.preventDefault();

       var title = $('#title').val();
       var description = $('#description').val();

       // console.log(title + '\n');
       // console.log(description);
       $.ajax({
           url: "../rest/rest.php/book",
           data: {
               'title': title,
               'description': description
           },
           type: 'POST',
           dataType: 'json',
           success: function (response) {
               console.log(response);
               //console.log(response['success']);
           },

           error: function (xhr, status, error) {
               console.log('error');
           }

       });
   });
});

其中#bookAdd是添加新书的形式,rest.php是添加了适当类并将书保存到DB的php脚本。 看起来像这样:

<?php
//load DB config
require_once __DIR__.'/config/db.php';


$response = [];
//connect to DB
try {
    $conn = new PDO(
        "mysql:host=".DB_HOST.";dbname=".DB_DB.";charset=utf8"
        , DB_LOGIN, DB_PASSWORD,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    $response = ['error' => 'DB Connection error: '.$e->getMessage()];
}

######### Dynamic load php class file depend on request #########
//parsing url
//if request URI is rest.php/book/1
//we will parse part book/1 and explode it
//to get name of class (book) and optional id from db (1)
$uriPathInfo = $_SERVER['PATH_INFO'];
//explode path info
$path = explode('/', $uriPathInfo);
$requestClass = $path[1];

//load class file
$requestClass = preg_replace('#[^0-9a-zA-Z]#', '', $requestClass);//remove all non alfanum chars from request
$className = ucfirst(strtolower($requestClass));

$classFile = __DIR__.'/class/'.$className.'.php';
require_once $classFile;

######### END DYNAMIC LOAD #########

$pathId = isset($path[2]) ? $path[2] : null;

if (!isset($response['error'])) {//process request if no db error
    include_once __DIR__.'/restEndpoints/'.$className.'.php';
}

header('Content-Type: application/json');//return json header

if (isset($response['error'])) {
    header("HTTP/1.0 400 Bad Request");//return proper http code if error
}

echo json_encode($response);

我找不到的是js文件中的成功功能-为什么控制台日志不显示任何内容?

尝试在浏览器中运行.php文件,看看它是否输出所需的结果。 也请尝试用php文件的绝对路径替换您的相对路径。

好的,我解决了这个问题:)在这里找到解决方案: jQuery AJAX调用返回[object Object] 只需在我的响应中调用函数stringify。 太...结论是我不能像json对象那样显示响应吗? 我对吗?

暂无
暂无

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

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