简体   繁体   English

使用Json从$ .ajax发送的PHP文件中获取数据

[英]Bring from a PHP file data sent by $.ajax using Json

As I need to bring separate data from a php file, and create an HTML piece to be injected with jQuery, I've choosen Json. 由于我需要从php文件中获取单独的数据,并创建要与jQuery一起插入的HTML片段,因此我选择了Json。

I send it from my PHP main file (between script tags) like this: 我从PHP主文件(在脚本标签之间)发送它,如下所示:

$.ajax({dataType: "json", url:'course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
    var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><a href="#"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></a></div></div><div class="contentColumn10"><div class="tableIconLink"><a href="#"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></a></div></div></div>';}

This sends properly editedCourseId value. 这将发送正确的editedCourseId值。 And what's inside course_generator.php is: course_generator.php里面是:

$courseId = $_POST['co_subj_co'];

$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);

$newCourseId = $result_co['co_id'];
$newCourseName = $result_co['co_name'];
$newCourseAbbrev = $result_co['co_abbrev'];
$newCourseTypeId = $result_co['co_fk_ct_id'];
$newCourseTypeName = $result_co['ct_name'];
$isMultisubjectValue = $result_co['co_multisubject'];

$newCourseValues = '{"newCourseId":'.$newCourseId.',"newCourseName":'.$newCourseName.',"newCourseAbbrev":'.$newCourseAbbrev.',"newCourseTypeId":'.$newCourseTypeId.',"newCourseTypeName":'.$newCourseTypeName.',"isMultisubjectValue":'.$isMultisubjectValue.'}';

I am afraid Im not receiving it properly by $courseId = $_POST['co_subj_co']; 恐怕我不能通过$courseId = $_POST['co_subj_co'];正确接收它$courseId = $_POST['co_subj_co']; , and neither $newCourseValues are being received properly on my main PHP file as my newCourseStructure is not generating anything. ,并且$newCourseValues都没有在我的主PHP文件中正确接收,因为newCourseStructure没有生成任何东西。 Could you please identify the several errors I am sure I'm making? 您能确定我确定正在犯的几个错误吗? Thank you. 谢谢。


UPDATE: 更新:

After changing my PHP main file to: 将我的PHP主文件更改为:

$.ajax({type : 'POST', dataType: "json", url:'config/forms/course_conf/course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><a href="#"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></a></div></div><div class="contentColumn10"><div class="tableIconLink"><a href="#"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></a></div></div></div>';}

And my course_generator.php file to: 而我的course_generator.php文件为:

$courseId = intval($_POST['co_subj_co']);
$subjectList = "";
$data ="";

$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);

$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
$outArr['newCourseAbbrev'] = $result_co['co_abbrev'];
$outArr['newCourseTypeId'] = $result_co['co_fk_ct_id'];
$outArr['newCourseTypeName'] = $result_co['ct_name'];
$outArr['isMultisubjectValue'] = $result_co['co_multisubject'];

$subjectsNum=mysql_num_rows(mysql_query("SELECT * FROM co_rel_subj WHERE co_subj_co = '$courseId'"));

$outArr['subjectsNum'] = $subjectsNum;
echo json_encode($outArr);

Instead of showing the HTML piece structured, this is what $newCourseStructure results: 这不是显示结构化的HTML片段,而是$newCourseStructure结果:

{"newCourseId":"243","newCourseName":"a","newCourseAbbrev":"ae","newCourseTypeId":"1","newCourseTypeName":"M\u00e1ster","isMultisubjectValue":"1","subjectList":"
Edici\u00f3n y Acabado de Imagen Digital<\/div>
","subjectsNum":1}

Your JSON string is not valid JSON because you don't use quotes around the string values. 您的JSON字符串不是有效的JSON,因为您没有在字符串值周围使用引号。 Instead of manually creating JSON, create an array or object and then json_encode() it. 无需手动创建JSON,而是创建一个数组或对象,然后对其进行json_encode()

You don't apper to output the JSON string. 您没有包装输出JSON字符串。 Use echo or print . 使用echoprint

Add dataType : 'json' to your ajax request so that jQuery will parse the JSON, returning the native JavaScript object. dataType : 'json'添加到您的ajax请求中,以便jQuery将解析JSON,并返回本地JavaScript对象。 All of the variables you use in the success function are undefined . 您在成功函数中使用的所有变量都是undefined After parsing the JSON you should use 解析JSON之后,您应该使用

var courseId = newCourse.newCourseId; // and so on

Your ajax request doesn't have a type and so will default to GET. 您的ajax请求没有类型,因此默认为GET。 add type : 'POST' if you want to use POST. 如果要使用POST,请添加type : 'POST'

Try $_GET['co_subj_co']; 尝试$_GET['co_subj_co']; instead of POST . 而不是POST

As long as you don't specify the method to jQuery's ajax call, it's made by GET, not POST. 只要您不为jQuery的ajax调用指定方法,它都是由GET而不是POST进行的。

Are you actually using POST, or are you firing off a GET request (your browser's developer tools should tell you this easily). 您实际上是在使用POST,还是正在触发GET请求(您的浏览器开发人员工具应该可以轻松地告诉您)。 You should also make sure that $courseId is an integer by $courseId = intval($_POST['co_cubj_co']); 您还应该通过$courseId = intval($_POST['co_cubj_co']);确保$courseId为整数$courseId = intval($_POST['co_cubj_co']); . In addition, you should add a condition for the event that the requested ID is not found. 此外,您应该为找不到请求的ID的事件添加条件。

As MueR suggests, the reason to make sure that courseID is an integer is to prevent SQL injection (unless you want people to do things like delete your entire DB at will). 正如MueR所建议的,确保courseID为整数的原因是为了防止SQL注入(除非您希望人们做一些事情,例如随意删除整个数据库)。 This, of course, assumes that courseID is something like an autoincrement int. 当然,这假定CourseID类似于autoincrement int。

However, you've got a number of other problems. 但是,您还有许多其他问题。 Your JSON is invalid since you're ostensibly writing out unquoted strings... you should just use json_encode: 您的JSON无效,因为您表面上写出未加引号的字符串...您应该只使用json_encode:

$outArr = array();
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
...
echo json_encode($outArr);

Personally, I prefer to just use $_REQUEST, which concatenates both $_POST and $_GET. 就个人而言,我更喜欢只使用$ _REQUEST,它将$ _POST和$ _GET串联在一起。 Makes it easier. 使其更容易。

I have annotated two things in the code: 我在代码中注释了两件事:

$.ajax({
    type : 'POST', 
    dataType: "json", 
    url:'config/forms/course_conf/course_generator.php',
    data:{
        co_subj_co:editedCourseId
    }})
    .done(function(newCourse){
        var courseId = newCourse.newCourseId;
        var newcourseName = newCourse.newCourseName;
        var isMultisubjectValue = newCourse.isMultisubjectValue;
        var subjectsNum = newCourse.subjectsNum;
        var newCourseAbbrev = newCourse.newCourseAbbrev;
        var newCourseTypeId = newCourse.newCourseTypeId;
        var newCourseTypeName = newCourse.newCourseTypeName;
        var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow"'
        + ' data-isMultisubjectValue="' + isMultisubjectValue + '"'
        + ' data-subjectsNum="' + subjectsNum + '"'
        + ' data-id="' + courseId + '"'
        + ' id="' + courseId + '"'
        + ' data-abbrev="' + newCourseAbbrev + '"'
        + ' data-courseTypeId="' + newCourseTypeId + '"'
        + ' title="' + newCourseName + '">'
        + '<div class="contentColumn40"><span class="tableContentText">'
        + newCourseName + ' (' + newCourseTypeName + ')</span></div>'
        // WHERE IS subjectList DEFINED?
        + '<div class="contentColumn40">' + subjectList 
        + '</div>'
        + '<div class="contentColumn10"><div class="tableIconLink">'
        + '<a href="#"><div class="editIcon" data-id="' + courseId + '"'
        + ' title="Editar ' + newCourseName + '"></div>'
        + '</a></div></div><div class="contentColumn10"><div class="tableIconLink">'
        + '<a href="#"><div data-id="'+courseId+'" class="discontinueIcon" '
        + 'title="Discontinuar '+newCourseName+'"></div></a></div></div></div>';
    /*
     * your HTML is generated, but you never put it in the DOM
     */
    $('#idOutputWrapper').empty().html(newCourseStructure);
}

When you use subjectList from the json response, please notice that it comes with a closing </div> tag for some reason, maybe you should change that, too. 当您使用json响应中的subjectList时,请注意由于某种原因它带有一个结束</div>标记,也许您也应该更改它。

btw: Your code formatting is horrible, sorry to say so. 顺便说一句:您的代码格式太糟糕了,不好意思这么说。 You can compress your js before uploading it to the server, but while working on it, it NEEDS to be readable. 您可以在将js上载到服务器之前对其进行压缩,但是在对其进行处理时,它需要可读性。 I just edited it to fit better in the codeblock here. 我只是对其进行了编辑,以使其更适合此处的代码块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM