There are so many ways to mock, but when it comes to connecting to a remote server and testing for real returns, it may be easier to mock with the item if there is no running node on the machine and there is PHP.
Copy Code code as follows:
<?php
/**
* Mock Json for Javascript
*
* @author Soulteary
* @date 2014-06-15
*/
/**
* Request Interface field: Character set
*/
Define (' CharSet ', ' CharSet ');
/**
* Request Interface Field: callback function name
*/
Define (' Callback ', ' callback ');
/**
* Request Interface field: cross-domain field
*/
Define (' Crossdomain ', ' cross-domain ');
/**
* Output mock data
* If a Mock.json file exists, the data is fetched from the Mock.js
*
* @return String
*/
Functionmockdata ()
{
if (file_exists (' Mock.json ')) {
$data =json_decode (file_get_contents (' Mock.json '));
}else{
$data =array (
' Code ' =>200,
' desc ' => ' get the default data. '
' Login ' =>true,
' Data ' =>array (
' Name ' => ' Test API. '
)
);
}
Returnjson_encode ($data);
}
/**
* Output character set, allowing the result to be GBK, gb2312, Utf-8
* If illegal or not set, output utf-8
*
* @return String
*/
Functioncharset ()
{
$ret = ' utf-8 ';
if (empty ($_request[charset])) {
Return$ret;
}else{
$charset =strtolower ($_request[charset]);
if (In_array ($charset, Array (' GBK ', ' gb2312 '), true) {
Return$charset;
}else{
Return$ret;
}
}
}
/**
* Assemble JSON data
*
* @return String
*/
Functionjsongenerator ()
{
if (!empty ($_request[callback])) {
Header (' Content-type:application/javascript charset= '. CharSet ());
Return$_request[callback]. " (". Mockdata ()."); ";
}else{
if (!empty ($_request[crossdomain])) {
Header ("Access-control-allow-origin: *");
};
Header (' Content-type:application/json charset= '. CharSet ());
Returnmockdata ();
}
}
/**
* Output Results
*/
Die (Jsongenerator ());
If you don't want to change the data object in PHP, and you're in trouble, then just change the JSON directly, and you might ask, why don't I just go to a JSON and answer:
1. You may need a callback to wrap this result;
2. You may expect this JSON to allow Cross-domain requests;
3. You may expect this JSON to customize the header encoding ...
Copy Code code as follows:
{
"Data": 1,
"W": "Test"
}
The code is very simple, not too much description.