开发者

Ajax issues, Invalid JSON

I'am building simple Ajax application (via jquery). I have strange issue. I found where the problem is, but I don't know how to solve it.

This is simple server-side php code:

<?php
require开发者_运维百科('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>

On the client side, the error "Invalid JSON" is thrown.

I have discovered that if I delete require function, everything work fine.

Just for information, the "some.php" is an empty php file. There is no error when I open direct php files.

So, conclusion: I cant use require or include function if I want to use ajax?


Use Firebug to see what you're actually getting back during the AJAX call. My guess is that there's a PHP error somewhere, so you're getting more than just JSON back from the call (Firebug will show you that). As for your conclusion: using include/require by itself has absolutely no effect on the AJAX call (assuming there are no errors).


Try changing:

<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>

To:

<?php
$return = array(
    'pageContent' => 'test'
);
echo json_encode($return);
?>

The problem might have to do with $return not being declared as an array prior to use.

Edit: Alright, so that might not be the problem at all. But! What might be happening is you might be echoing out something in the response. For example, if you have an error echoing out prior to the JSON, you'd be unable to parse it on the client.


if the "some.php" is an empty php file, why do you require it at all?!

require function throws a fatal error if it could't require the file. try using include function instead and see what happens, if it works then you probably have a problem with require 'some.php';


A require call won't have any effect. You need to check your returned output in Firebug. If using Chrome there is a plugin called Simple REST Client. https://chrome.google.com/extensions/detail/fhjcajmcbmldlhcimfajhfbgofnpcjmb through which you can quickly query for stuff.

Also, it's always good to send back proper HTTP headers with your response showing the response type.


It's most likely the BOM as has been discussed above. I had the same problem multiple times and used Fiddler to check the file in hex and noticed an extra 3 bytes that didn't exist in a prior backup and in new files I created. Somehow my original files were getting modified by Textpad (both in Windows). Although when I created them in Notepad++ I was fine.

So make sure that you have your encoding and codepages set up properly when you create, edit, and save your files in addition to keeping that consistent across OSes if you're developing on windows let's say and publishing to a linux environment at your hosting provider.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜