Calling Function

Asked

Viewed 63 times

0

I’m starting in javascript and I’m having a question. What is the best way to pass instructions to a Javascript Function, I will give a current example of the way I am doing, works, but is a good practice ?

sistema('/comando2'); //estou chamando assim



        sistema(cmd)
        {  if((req.state == 4) && (req.status == 200))//verifica a request do XMLHttpRequest
            {   
                if(cmd.search("/comando1")>=0) {faz algo//}
                if(cmd.search("/comando2")>=0) {faz algo//}

                }

        }

I would also like to know a good practice to create a requests Function with Xmlhttprequest, in which I change the URL parameter and values according to need, and properly handle errors.

Thank you

  • You can explain what functionality sistema does in your code?

  • A file manager, it changes according to the value of "cmd"

  • If you can explain it further and give examples, I’ll be able to answer it more correctly. Otherwise the way you’re doing sounds good, but I can’t imagine the use of that function.

  • I want for example to click on a rename button, when clicking call Function with the parameter "/rename/file", then inside it do a search and check if there is the rename command, and then split to remove only the file name and send to a request with the api.

  • Okay, and this one sistema makes an ajax call before or after the if(cmd.search)?

  • cmd Search is used to fill the api url and the value that will be sent with Xmlhttprequest

Show 1 more comment

1 answer

1


To use the .search you have to pass a Regexp. In your example you’re passing a String.

Since your input is a string, then you can use the .includes() or the indexOf.

So I could stay:

function sistema(cmd) {
  if (cmd.includes("/comando1")) {
    console.log(1);
  }
  if (cmd.includes("/comando2")) {
    console.log(2);
  }
}

sistema('/comando2');
sistema('/comando2');
sistema('/comando1');

I don’t quite understand how you want to use the req.state in this function because it belongs to ajax and that code is not in the question as it is probably not related to the problem. So I took that from the answer and just focused on the question of detecting the right command.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.