AJAX返回通过jQuery.ajax发送的数据的问题

时间:2022-10-07 17:00:26

I am trying to receive a json object back from php after sending data to the php file from the js file.

我试图从js文件发送数据到PHP文件后从PHP接收一个json对象。

All I get is undefined.

我得到的都是未定义的。

Here are the contents of the php and js file.

这是php和js文件的内容。

data.php

data.php

<?php

$action = $_GET['user'];

$ action = $ _GET ['user'];

$data = array( "first_name" => "Anthony", "last_name" => "Garand", "email" => "anthonygarand@gmail.com", "password" => "changeme");

$ data = array(“first_name”=>“Anthony”,“last_name”=>“Garand”,“email”=>“anthonygarand@gmail.com”,“password”=>“changeme”);

switch ($action) { case 'anthonygarand@gmail.com': echo $_GET['callback'] . '('. json_encode($data) . ');'; break; }

switch($ action){case'anthonygarand@gmail.com':echo $ _GET ['callback']。 '('。json_encode($ data)。');';打破; }

?>

?>

core.js

core.js

$(document).ready(function(){
$.ajax({    url: "data.php", 
            data: {"user":"anthonygarand@gmail.com"}, 
            context: document.body, 
            data: "jsonp",
            success: function(data){renderData(data);}
            });

});

});

function renderData(data) { document.write(data.first_name); }

function renderData(data){document.write(data.first_name); }

1 个解决方案

#1


1  

It looks like you have two data options set in the Ajax function. Instead of the line

看起来您在Ajax函数中设置了两个数据选项。而不是线

data: "jsonp",

You need

你需要

dataType: "jsonp"

As you're not actually passing the PHP file any information.

因为你实际上没有传递PHP文件的任何信息。

Another couple of things, make sure you're getting valid JSON (jsonlint.com), we had a similar issue and it turned out we had the wrong kind of quotes.

另外几件事,确保你获得了有效的JSON(jsonlint.com),我们遇到了类似的问题,结果我们得到了错误的报价。

Lastly: You MAY need to JSON.parse(data) to see convert it to an object at Javascript's end.

最后:您可能需要使用JSON.parse(数据)来查看将其转换为Javascript结尾的对象。

#1


1  

It looks like you have two data options set in the Ajax function. Instead of the line

看起来您在Ajax函数中设置了两个数据选项。而不是线

data: "jsonp",

You need

你需要

dataType: "jsonp"

As you're not actually passing the PHP file any information.

因为你实际上没有传递PHP文件的任何信息。

Another couple of things, make sure you're getting valid JSON (jsonlint.com), we had a similar issue and it turned out we had the wrong kind of quotes.

另外几件事,确保你获得了有效的JSON(jsonlint.com),我们遇到了类似的问题,结果我们得到了错误的报价。

Lastly: You MAY need to JSON.parse(data) to see convert it to an object at Javascript's end.

最后:您可能需要使用JSON.parse(数据)来查看将其转换为Javascript结尾的对象。