Can't get json data from jQuery ajax call

后端 未结 5 1088
深忆病人
深忆病人 2021-01-05 09:35

I\'m trying to get data from data.php via jQuery ajax call.

My code looks like this:

var jsonData;

$.ajax({
        url: \'data.php\',
         


        
相关标签:
5条回答
  • 2021-01-05 09:52

    PHP

    try {
        $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->query('SET NAMES utf8;');
        $stmt = $dbh->prepare($sql);  
        //$stmt->bindParam("id", $_GET[id]);
        $stmt->execute();
    
        $advice = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbh = null;
        echo '{"items":'. json_encode($advice) .'}'; 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
    

    Ajax

     var temp;
        $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: serviceurl,
                data: "{'userName':'" + userName + "' , 'password': '" + password                                   
                       + "'}",
                dataType: "json",
                success: function(msg) {
                                temp = jQuery.parseJSON(msg.d);
                              },
                error: function(xhr, ajaxOptions, thrownError) {}
    
            });
    
    0 讨论(0)
  • 2021-01-05 09:53

    You should be using header() function in your PHP to set the proper response header (content type and charset):

    header('Content-type: application/json; charset=UTF-8');
    

    You should also repeat this at the top of HTML pages:

    <meta http-equiv="Content-type" value="text/html; charset=UTF-8" />
    

    See also:

    PHP UTF-8 cheatsheet

    0 讨论(0)
  • 2021-01-05 10:04

    Try to put dataType: 'json' in you ajax call:

    var jsonData;
    
    $.ajax({
            url: 'data.php',
            dataType: 'json',
            success: function(response) {
                jsonData = response;
            }
    });
    
    0 讨论(0)
  • 2021-01-05 10:05

    Also you can use this mechanism:

    $.getJSON( "data.php", function( response ) {
        jsonData = response;
    });
    

    It is more clean if you want get only JSON :)

    0 讨论(0)
  • 2021-01-05 10:12

    data.php

    header('Content-type: application/json'); 
    

    and

    $.ajax({
            url: 'data.php',
            dataType: 'json',
            success: function(response) {
                jsonData = response;
            }
    });
    
    0 讨论(0)
提交回复
热议问题