首页 > 解决方案 > 如何将数据从 PHP 文件 1 发送到包含 JSON 代码的 PHP 文件 2?

问题描述

我是 API 的新手,所以我创建了两个 .php 文件:

1- file1.php(包括从用户示例中获取数据的 HTML 表单:代码和描述输入)

2- file2.php(包括接受输入并返回输出消息的 Json 代码)

例子:

file2.php 应具有以下 Json 格式:

{
"STATUS_CODE" : "AP 2013",
"STATUS_DESCRIPTION" : "Amazing Pi3232",
}

从 Postman 或 JMeter 执行 Json 格式后,将出现以下结果:

{"message":"Status was created."}

问题:

如何将上述输入从 file1.php 发送到 file2.php 以及如何从 API 检索返回的消息?

标签: phpjsonapi

解决方案


我用过这个,效果很好,谢谢亲爱的。

//Submit Form with Form fields              
        $(document).ready(function(){
            $("#SubmitFormSeetStatus").click(function(){

                // Show that Feedback something is loading
                // $("#Loading").show();
                $("#Loading").html("<b>Loading response...</b>");

                //To debug
                //alert("You've clicked the link.");


                 //Send Json format to Create a Seed Status and get the response
                $.ajax({
                    url: 'Path of the .php file',
                    dataType: 'json',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify({ 
                        'STATUS_CODE': $("#STATUS_CODE").val(), 
                        'STATUS_DESCRIPTION': $("#STATUS_DESCRIPTION").val(),
                        'STATUS_ALT_DESCRIPTION': $("#STATUS_ALT_DESCRIPTION").val(),
                        'STATUS_ACTIVE': $("#STATUS_ACTIVE").val(),

                    }),

                    processData: false,
                    success: function( data, textStatus, jQxhr ){

                        // Get Json response as a string
                        var JsonResponse= JSON.stringify( data );

                        //Get response as Json format to be able to get each value
                        var obj = JSON.parse(JsonResponse);

                            //To debug
                            //var p = obj.message;
                            //console.log( p );

                        //Print Object value inside the html by specific key
            document.getElementById("Successalertmsg").innerHTML = obj.message;

                        $("#alertmsgfeedback").show();

                        //$('#response').html( $JsonResponse );
                        $("#Loading").hide();
                    },
                    error: function( jqXhr, textStatus, errorThrown ){
                        console.log( errorThrown );
                        alert( "Some fields are empty please fill them!");
                        $("#Loading").hide();

                    }
                });
            });
        });

推荐阅读