PC1.PC http://www.bitscn.com/pdb/php/201411/402... 21Yii2 PCPHPApi 1url2file_get_contents( )url3JSON4http://www.jb51.net/article/20705.htm //PHPURL $url='http://api.xx"/> PC1.PC http://www.bitscn.com/pdb/php/201411/402... 21Yii2 PCPHPApi 1url2file_get_contents( )url3JSON4http://www.jb51.net/article/20705.htm //PHPURL $url='http://api.xx">
search
HomeBackend DevelopmentPHP TutorialNotes and precautions for calling the interface on PC, precautions in late pregnancy, precautions when flying, precautions after miscarriage

data-id="1190000004902725">

Preface

Good habits create a good life, and you must be good at summarizing during development. Today I will continue to share some useful information with you. Fans who follow me will benefit from it. Below are some notes I compiled when calling the interface on the PC, as well as reminders of things you need to pay attention to!

Cause Analysis

1. First, let me talk about why the interface is called on the PC side to obtain data!
I’ll give you a link: http://www.bitscn.com/pdb/php/201411/402…. After reading this article, you will probably understand what I mean.
2. Integrating relevant information is not only conducive to the acquisition of information, but also serves as a lesson for others. People who have planted trees can benefit future generations, right? Haha, I am a philanthropist.

Note organization

1. Three ways for Yii2 PC to call the interface to obtain data

PHP method to call the Api interface

<code>    1、直接在方法里引用接口的url。
    2、通过file_get_contents()函数获取url的数据。
    3、把获取到的JSON格式数据进行反转。(可选)
    4、参考网址:http://www.jb51.net/article/20705.htm   //PHP远程调用URL
        例: $url='http://api.xxx.com/v1/departments?id=list&company_id=1';
             $data=file_get_contents($url);
             $data_1 = json_decode($data,true);     //JSON反转</code>

Ajax method to call the Api interface

<code>    例:
        $.ajax({
        type:"POST",
        url: //你的请求程序页面随便啦(接口地址)
        async:false,//同步:意思是当有返回值以后才会进行后面的js程序。
        data://请求需要发送的处理数据
        success:function(msg){
            if (msg) {//根据返回值进行跳转
                window.location.href = '你的跳转的目标地址(页面地址)';
            }
        }</code>

JQ method to call the Api interface

<code>例:
        <script type="text/javascript" src="/apihandonesvn/frontend/web/assets/68738eee/jquery-1.11.2.min.js"></script>
        <script type="text/javascript">
            //1&#12289;GET&#26041;&#24335;
            $.get('http://api.XXX.com/v1/departments?grade=1',function(data){ 
                    //  console.log(data);//&#36755;&#20986;&#20869;&#23481;&#65292;&#31867;&#20284;alert()
                     $('#content').html(data);
            });

            //2&#12289;POST&#26041;&#24335;
            $.post('http://api.XXX.com/v1/departments?grade=1',{a:1,b:2,c:3},function(data){ 
                     $('#content').html(JSON.stringify(data));
            });

        </script></code>

Added: If you use the latter two methods, add the following code at the top of all methods of the controller corresponding to the interface

<code> public function behaviors()
    {
        return ArrayHelper::merge([
            [
                 'class' => Cors::className(),
                 'cors' => [
                     'Origin' => ['http://www.ceshi.com'],//PC端的Url
                     'Access-Control-Request-Method' => ['GET','POST','PUT','DELETE', 'HEAD', 'OPTIONS'],
                 ],

                'actions' => [
                    'index' => [
                        'Access-Control-Allow-Credentials' => true,
                    ]
                ]
            ],
        ],
            parent::behaviors());
    }</code>

The above three methods of calling the interface on the PC side have been tested by me and are all feasible. You can choose what you like.

2. When calling the interface on the PC, how does the interface obtain the uid?
At this time, the interface cannot be obtained using Yii:$app->user->id that comes with Yii, because it is impossible to log in through the interface. To obtain the uid of the current logged-in user through the interface, you can pass an access-token through the PC, and then use get on the interface to find out the uid and solve the problem.
This method can also be imitated when the interface obtains other parameters.

3. Report: PHP Warning – yiibaseErrorException
Invalid argument supplied for foreach() error problem and solution
This error is caused by looping empty data. As long as a judgment must be added before the data is looped to ensure that the data exists before the loop can be looped. solved. Although this is not a particularly difficult error to solve, we still have to pay attention to details, as details determine success or failure.

Reminder

1. The PC calls the interface for local testing. It is best not to match the local interface address with the Internet, because then it will go to the local interface first. If the local interface is good, it is difficult to find the reason.

Related information

PHP (CURL) POST data calling API simple example: http://eyexiaobo.iteye.com/blog/1100712

The above introduces the notes and precautions for calling the interface on the PC side, including precautions and interface content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor