我想将我的Ajax请求结果保存到文件中
看看我的代码:
function getAjax(id) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/users/"+id,
type: 'GET',
dataType: 'JSON',
success: function(result) {
console.log(result)
$('#name').html(result.name)
$('#email').html(result.email)
$('#id').html(result.id)
$('#company').html(result.company.name)
$('#adress').html(result.address.street)
$('#suite').html(result.address.suite)
$('#city').html(result.address.city)
$('#zipcode').html(result.address.zipcode)
$('#geolatt').html(result.address.geo.lat)
$('#geolong').html(result.address.geo.lng)
在这里,我将使用以下方法将结果保存到文件中:
date_default_timezone_set("Europe/Paris");
$line = ""; // MY DATA HERE
$file = 'visitors.log';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
fwrite($fr, "$line");
fwrite($fr, $oldContents);
fclose($fr);
感谢您的帮助
答案 0 :(得分:0)
我会将另一个ajax调用嵌套到您的php服务器。
function saveToServer(result)
{
$.ajax(
{
url: "/somepath/somepage.php",
type: 'POST',
dataType: 'JSON',
data: { MyDatas: result },
success: function()
{
//Hooray
}
}
}
function getAjax(id)
{
$.ajax(
{
url: "https://jsonplaceholder.typicode.com/users/"+id,
type: 'GET',
dataType: 'JSON',
success: function(result)
{
saveToServer(result);
console.log(result);
/*
* your code
*/
}
}
}
然后在服务器端/somepath/somepage.php
:
if (isset($_POST['MyDatas']))
{
//save to file the content of $_POST['MyDatas']
}