Special characters break json returned to jQuery

我是研究僧i 提交于 2019-12-24 06:27:45

问题


The following jQuery ajax function runs a PHP script that queries a MySQL database containing entries that are encoded as UTF-8:

function searchLocations() {

    var stateSelected = $("#stateSelect").val();

    $.ajax({
        url: 'ajax/json.php',
        dataType: 'json',
        data: 'state='+stateSelected,
        success: function(data) {
            placeMarkers(data.markerdata.markers);
        }
    });

}

The JSON object returned to the function contains the longitudes and latitudes of map marker objects as well as a name to display in an info window when each marker is clicked.

Every name loads fine, and is displayed without a problem except for a single name which contains the character "ñ". This name is returned in the JSON object as "null". How can I make this name display properly?


回答1:


I used to have this problem and I found there was two options:

  1. In PHP convert all characters into HTML friendly characters using the PHP function htmlentities (http://php.net/manual/en/function.htmlentities.php) before returning it to the jQuery function.
  2. If that fails or the characters are not converted you could try using base64 encode and decode. In PHP you can encode the data using base64_encode function (http://php.net/manual/en/function.base64-encode.php). Then in jQuery you could use one of many base64 encode and decode plugins to decode the data. I have used this plugin successfully in the past: http://plugins.jquery.com/project/base64-encode-and-decode

Failing both those options it may be worth looking at the character set used by your page. Try and use UTF-8 to encode your HTML and see if that helps.

Without using jQuery and AJAX if you did a basic PHP page that queried the data in question and prints the name out does it still not display correctly. If it doesn't it could also be a character set issue with MySQL.

Hope any of these pointers help. Let me know how you get on.



来源:https://stackoverflow.com/questions/7084578/special-characters-break-json-returned-to-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!