简体   繁体   English

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

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

I'm really new in Ajax with PHP and JavaScript. 我对使用PHP和JavaScript的Ajax真的很陌生。 I have to do some simple project as a workshop for my training and I created js script: 我必须做一个简单的项目作为培训班,并创建了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');
           }

       });
   });
});

Where #bookAdd is form to add new book and rest.php is php script where proper class is added and book is saving to DB. 其中#bookAdd是添加新书的形式,rest.php是添加了适当类并将书保存到DB的php脚本。 It looks like this: 看起来像这样:

<?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);

The thing I can't find out is success function in my js file - why console log doesn't display anything? 我找不到的是js文件中的成功功能-为什么控制台日志不显示任何内容?

Try to run the .php file in browser and see if it outputs the desired results. 尝试在浏览器中运行.php文件,看看它是否输出所需的结果。 Also try to replace your relative path with absolute path of the php file. 也请尝试用php文件的绝对路径替换您的相对路径。

Ok i fix this :) found solution here: jQuery AJAX call returns [object Object] . 好的,我解决了这个问题:)在这里找到解决方案: jQuery AJAX调用返回[object Object] Just had to call function stringify at my response. 只需在我的响应中调用函数stringify。 Soo...conclusion is I can't display response just like that as json object? 太...结论是我不能像json对象那样显示响应吗? Am I right? 我对吗?

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

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